PageSourceSearch

https://jingwei-xu-00-eccv2026-cad-challenge.hf.space/assets/StaticAudio-DPMwTtB7.js

js jingwei-xu-00-eccv2026-cad-challenge.hf.space collected 2026-10-03 16:59:44 UTC 426,648 bytes, 27 lines download raw bytes

1import{p as se,v as Xn,d as ht,J as Qn,i as Fe,f as Hs,b as wr,a as Ct,M as Mt,A as Jn}from"./i18n-zlFzjs4f.js";import{a as Se,f as ai,ah as kr,M as ms,a7 as oi,ac as Ke,t as xt,O as ps,R as Oe,aa as _e,ab as Zn,Z as P,$ as ge,Q as Te,T as ye,S as ve,X as Pr,N as lt,v as ea,U as xs,a2 as nt,a3 as Fr}from"./index-CU1DelDP.js";import{I as ta}from"./ScrollFade.svelte_svelte_type_style_lang-Dfs1lduW.js";import{B as sa}from"./BlockLabel-BxeW21ay.js";import{D as ia}from"./DownloadLink-X1fLUNGO.js";import{E as Or}from"./Empty-DKf4Jzxn.js";import{S as ra}from"./ShareButton-D1503whi.js";import{D as na}from"./Download-CO-8BDZB.js";import{M as Vs}from"./Music-D7bidyQL.js";import{I as aa}from"./IconButtonWrapper-CH_og5Tr.js";import{g as Nt,u as oa,p as la,s as Ii,M as ca}from"./MinimalAudioPlayer-CALg8PS6.js";import{V as ha,P as ua,T as da}from"./VolumeLevels-DsTK7Wav.js";import{P as fa}from"./Play-BB6GHN5a.js";import{U as ga}from"./Undo-BVgZOkIa.js";var ma=ai('<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="currentColor" stroke-width="1.5" viewBox="0 0 24 24" color="currentColor"><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M21.044 5.704a.6.6 0 0 1 .956.483v11.626a.6.6 0 0 1-.956.483l-7.889-5.813a.6.6 0 0 1 0-.966l7.89-5.813ZM10.044 5.704a.6.6 0 0 1 .956.483v11.626a.6.6 0 0 1-.956.483l-7.888-5.813a.6.6 0 0 1 0-.966l7.888-5.813Z"></path></svg>');function pa(a){var e=ma();Se(a,e)}var Ea=ai('<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" class="feather feather-closed-caption"><rect x="2" y="6" width="20" height="12" rx="2" ry="2"></rect><text x="12" y="15" font-family="sans-serif" font-size="8" font-weight="bold" fill="currentColor" stroke="none" text-anchor="middle">CC</text></svg>');function Ta(a){var e=Ea();Se(a,e)}var ya=ai('<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="currentColor" stroke-width="1.5" viewBox="0 0 24 24" color="currentColor"><path stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" d="M2.956 5.704A.6.6 0 0 0 2 6.187v11.626a.6.6 0 0 0 .956.483l7.889-5.813a.6.6 0 0 0 0-.966l-7.89-5.813ZM13.956 5.704a.6.6 0 0 0-.956.483v11.626a.6.6 0 0 0 .956.483l7.889-5.813a.6.6 0 0 0 0-.966l-7.89-5.813Z"></path></svg>');function va(a){var e=ya();Se(a,e)}class Mr{constructor(){this.listeners={}}on(e,t,s){if(this.listeners[e]||(this.listeners[e]=new Set),s?.once){const i=(...r)=>{this.un(e,i),t(...r)};return this.listeners[e].add(i),()=>this.un(e,i)}return this.listeners[e].add(t),()=>this.un(e,t)}un(e,t){var s;(s=this.listeners[e])===null||s===void 0||s.delete(t)}once(e,t){return this.on(e,t,{once:!0})}unAll(){this.listeners={}}emit(e,...t){this.listeners[e]&&this.listeners[e].forEach((s=>s(...t)))}}class xa extends Mr{constructor(e){super(),this.subscriptions=[],this.isDestroyed=!1,this.options=e}onInit(){}_init(e){this.isDestroyed&&(this.subscriptions=[],this.isDestroyed=!1),this.wavesurfer=e,this.onInit()}destroy(){this.emit("destroy"),this.subscriptions.forEach((e=>e())),this.subscriptions=[],this.isDestroyed=!0,this.wavesurfer=void 0}}function qt(a,e,t,s,i=3,r=0,n=100){if(!a)return()=>{};const o=matchMedia("(pointer: coarse)").matches;let l=()=>{};const c=h=>{if(h.button!==r)return;h.preventDefault(),h.stopPropagation();let u=h.clientX,d=h.clientY,g=!1;const f=Date.now(),m=A=>{if(A.preventDefault(),A.stopPropagation(),o&&Date.now()-f<n)return;const x=A.clientX,D=A.clientY,R=x-u,C=D-d;if(g||Math.abs(R)>i||Math.abs(C)>i){const k=a.getBoundingClientRect(),{left:I,top:w}=k;g||(t?.(u-I,d-w),g=!0),e(R,C,x-I,D-w),u=x,d=D}},E=A=>{if(g){const x=A.clientX,D=A.clientY,R=a.getBoundingClientRect(),{left:C,top:k}=R;s?.(x-C,D-k)}l()},T=A=>{A.relatedTarget&&A.relatedTarget!==document.documentElement||E(A)},y=A=>{g&&(A.stopPropagation(),A.preventDefault())},v=A=>{g&&A.preventDefault()};document.addEventListener("pointermove",m),document.addEventListener("pointerup",E),document.addEventListener("pointerout",T),document.addEventListener("pointercancel",T),document.addEventListener("touchmove",v,{passive:!1}),document.addEventListener("click",y,{capture:!0}),l=()=>{document.removeEventListener("pointermove",m),document.removeEventListener("pointerup",E),document.removeEventListener("pointerout",T),document.removeEventListener("pointercancel",T),document.removeEventListener("touchmove",v),setTimeout((()=>{document.removeEventListener("click",y,{capture:!0})}),10)}};return a.addEventListener("pointerdown",c),()=>{l(),a.removeEventListener("pointerdown",c)}}function Nr(a,e){const t=e.xmlns?document.createElementNS(e.xmlns,a):document.createElement(a);for(const[s,i]of Object.entries(e))if(s==="children"&&i)for(const[r,n]of Object.entries(i))n instanceof Node?t.appendChild(n):typeof n=="string"?t.appendChild(document.createTextNode(n)):t.appendChild(Nr(r,n));else s==="style"?Object.assign(t.style,i):s==="textContent"?t.textContent=i:t.setAttribute(s,i.toString());return t}function _t(a,e,t){const s=Nr(a,e||{});return t?.appendChild(s),s}class Di extends Mr{constructor(e,t,s=0){var i,r,n,o,l,c,h,u,d,g;super(),this.totalDuration=t,this.numberOfChannels=s,this.element=null,this.minLength=0,this.maxLength=1/0,this.contentEditable=!1,this.subscriptions=[],this.updatingSide=void 0,this.isRemoved=!1,this.subscriptions=[],this.id=e.id||`region-${Math.random().toString(32).slice(2)}`,this.start=this.clampPosition(e.start),this.end=this.clampPosition((i=e.end)!==null&&i!==void 0?i:e.start),this.drag=(r=e.drag)===null||r===void 0||r,this.resize=(n=e.resize)===null||n===void 0||n,this.resizeStart=(o=e.resizeStart)===null||o===void 0||o,this.resizeEnd=(l=e.resizeEnd)===null||l===void 0||l,this.color=(c=e.color)!==null&&c!==void 0?c:"rgba(0, 0, 0, 0.1)",this.minLength=(h=e.minLength)!==null&&h!==void 0?h:this.minLength,this.maxLength=(u=e.maxLength)!==null&&u!==void 0?u:this.maxLength,this.channelIdx=(d=e.channelIdx)!==null&&d!==void 0?d:-1,this.contentEditable=(g=e.contentEditable)!==null&&g!==void 0?g:this.contentEditable,this.element=this.initElement(),this.setContent(e.content),this.setPart(),this.renderPosition(),this.initMouseEvents()}clampPosition(e){return Math.max(0,Math.min(this.totalDuration,e))}setPart(){var e;const t=this.start===this.end;(e=this.element)===null||e===void 0||e.setAttribute("part",`${t?"marker":"region"} ${this.id}`)}addResizeHandles(e){const t={position:"absolute",zIndex:"2",width:"6px",height:"100%",top:"0",cursor:"ew-resize",wordBreak:"keep-all"},s=_t("div",{part:"region-handle region-handle-left",style:Object.assign(Object.assign({}
1,t),{left:"0",borderLeft:"2px solid rgba(0, 0, 0, 0.5)",borderRadius:"2px 0 0 2px"})},e),i=_t("div",{part:"region-handle region-handle-right",style:Object.assign(Object.assign({},t),{right:"0",borderRight:"2px solid rgba(0, 0, 0, 0.5)",borderRadius:"0 2px 2px 0"})},e);this.subscriptions.push(qt(s,(r=>this.onResize(r,"start")),(()=>null),(()=>this.onEndResizing("start")),1),qt(i,(r=>this.onResize(r,"end")),(()=>null),(()=>this.onEndResizing("end")),1))}removeResizeHandles(e){const t=e.querySelector('[part*="region-handle-left"]'),s=e.querySelector('[part*="region-handle-right"]');t&&e.removeChild(t),s&&e.removeChild(s)}initElement(){if(this.isRemoved)return null;const e=this.start===this.end;let t=0,s=100;this.channelIdx>=0&&this.numberOfChannels>0&&this.channelIdx<this.numberOfChannels&&(s=100/this.numberOfChannels,t=s*this.channelIdx);const i=_t("div",{style:{position:"absolute",top:`${t}%`,height:`${s}%`,backgroundColor:e?"none":this.color,borderLeft:e?"2px solid "+this.color:"none",borderRadius:"2px",boxSizing:"border-box",transition:"background-color 0.2s ease",cursor:this.drag?"grab":"default",pointerEvents:"all"}});return!e&&this.resize&&this.addResizeHandles(i),i}renderPosition(){if(!this.element)return;const e=this.start/this.totalDuration,t=(this.totalDuration-this.end)/this.totalDuration;this.element.style.left=100*e+"%",this.element.style.right=100*t+"%"}toggleCursor(e){var t;this.drag&&(!((t=this.element)===null||t===void 0)&&t.style)&&(this.element.style.cursor=e?"grabbing":"grab")}initMouseEvents(){const{element:e}=this;e&&(e.addEventListener("click",(t=>this.emit("click",t))),e.addEventListener("mouseenter",(t=>this.emit("over",t))),e.addEventListener("mouseleave",(t=>this.emit("leave",t))),e.addEventListener("dblclick",(t=>this.emit("dblclick",t))),e.addEventListener("pointerdown",(()=>this.toggleCursor(!0))),e.addEventListener("pointerup",(()=>this.toggleCursor(!1))),this.subscriptions.push(qt(e,(t=>this.onMove(t)),(()=>this.toggleCursor(!0)),(()=>{this.toggleCursor(!1),this.drag&&this.emit("update-end")}))),this.contentEditable&&this.content&&(this.contentClickListener=t=>this.onContentClick(t),this.contentBlurListener=()=>this.onContentBlur(),this.content.addEventListener("click",this.contentClickListener),this.content.addEventListener("blur",this.contentBlurListener)))}_onUpdate(e,t,s){var i;if(!(!((i=this.element)===null||i===void 0)&&i.parentElement))return;const{width:r}=this.element.parentElement.getBoundingClientRect(),n=e/r*this.totalDuration;let o=t&&t!=="start"?this.start:this.start+n,l=t&&t!=="end"?this.end:this.end+n;const c=s!==void 0;c&&this.updatingSide&&this.updatingSide!==t&&(this.updatingSide==="start"?o=s:l=s),o=Math.max(0,o),l=Math.min(this.totalDuration,l);const h=l-o;this.updatingSide=t;const u=h>=this.minLength&&h<=this.maxLength;o<=l&&(u||c)&&(this.start=o,this.end=l,this.renderPosition(),this.emit("update",t))}onMove(e){this.drag&&this._onUpdate(e)}onResize(e,t){this.resize&&(this.resizeStart||t!=="start")&&(this.resizeEnd||t!=="end")&&this._onUpdate(e,t)}
1onEndResizing(e){this.resize&&(this.emit("update-end",e),this.updatingSide=void 0)}onContentClick(e){e.stopPropagation(),e.target.focus(),this.emit("click",e)}onContentBlur(){this.emit("update-end")}_setTotalDuration(e){this.totalDuration=e,this.renderPosition()}play(e){this.emit("play",e&&this.end!==this.start?this.end:void 0)}getContent(e=!1){var t;return e?this.content||void 0:this.element instanceof HTMLElement?((t=this.content)===null||t===void 0?void 0:t.innerHTML)||void 0:""}setContent(e){var t;if(this.element)if(this.content&&this.contentEditable&&(this.contentClickListener&&this.content.removeEventListener("click",this.contentClickListener),this.contentBlurListener&&this.content.removeEventListener("blur",this.contentBlurListener)),(t=this.content)===null||t===void 0||t.remove(),e){if(typeof e=="string"){const s=this.start===this.end;this.content=_t("div",{style:{padding:`0.2em ${s?.2:.4}em`,display:"inline-block"},textContent:e})}else this.content=e;this.contentEditable&&(this.content.contentEditable="true",this.contentClickListener=s=>this.onContentClick(s),this.contentBlurListener=()=>this.onContentBlur(),this.content.addEventListener("click",this.contentClickListener),this.content.addEventListener("blur",this.contentBlurListener)),this.content.setAttribute("part","region-content"),this.element.appendChild(this.content),this.emit("content-changed")}else this.content=void 0}setOptions(e){var t,s;if(this.element){if(e.color&&(this.color=e.color,this.element.style.backgroundColor=this.color),e.drag!==void 0&&(this.drag=e.drag,this.element.style.cursor=this.drag?"grab":"default"),e.start!==void 0||e.end!==void 0){const i=this.start===this.end;this.start=this.clampPosition((t=e.start)!==null&&t!==void 0?t:this.start),this.end=this.clampPosition((s=e.end)!==null&&s!==void 0?s:i?this.start:this.end),this.renderPosition(),this.setPart()}if(e.content&&this.setContent(e.content),e.id&&(this.id=e.id,this.setPart()),e.resize!==void 0&&e.resize!==this.resize){const i=this.start===this.end;this.resize=e.resize,this.resize&&!i?this.addResizeHandles(this.element):this.removeResizeHandles(this.element)}e.resizeStart!==void 0&&(this.resizeStart=e.resizeStart),e.resizeEnd!==void 0&&(this.resizeEnd=e.resizeEnd)}}remove(){this.isRemoved=!0,this.emit("remove"),this.subscriptions.forEach((e=>e())),this.element&&(this.element.remove(),this.element=null)}}class li extends xa{constructor(e){super(e),this.regions=[],this.regionsContainer=this.initRegionsContainer()}static create(e){return new li(e)}onInit(){if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");this.wavesurfer.getWrapper().appendChild(this.regionsContainer),this.subscriptions.push(this.wavesurfer.on("ready",(t=>{this.regions.forEach((s=>s._setTotalDuration(t)))})));let e=[];this.subscriptions.push(this.wavesurfer.on("timeupdate",(t=>{const s=this.regions.filter((i=>i.start<=t&&(i.end===i.start?i.start+.05:i.end)>=t));s.forEach((i=>{e.includes(i)||this.emit("region-in",i)})),e.forEach((i=>{s.includes(i)||this.emit("region-out",i)})),e=s})))}initRegionsContainer(){return _t("div",{part:"regions-container",style:{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",zIndex:"5",pointerEvents:"none"}})}getRegions(){return this.regions}avoidOverlapping(e){e.content&&setTimeout((()=>{const t=e.content,s=t.getBoundingClientRect(),i=this.regions.map((r=>{if(r===e||!r.content)return 0;const n=r.content.getBoundingClientRect();return s.left<n.left+n.width&&n.left<s.left+s.width?n.height:0})).reduce(((r,n)=>r+n),0);t.style.marginTop=`${i}px`}),10)}adjustScroll(e){var t,s;if(!e.element)return;const i=(s=(t=this.wavesurfer)===null||t===void 0?void 0:t.getWrapper())===null||s===void 0?void 0:s.parentElement;if(!i)return;const{clientWidth:r,scrollWidth:n}=i;if(n<=r)return;const o=i.getBoundingClientRect(),l=e.element.getBoundingClientRect(),c=l.left-o.left,h=l.right-o.left;c<0?i.scrollLeft+=c:h>r&&(i.scrollLeft+=h-r)}virtualAppend(e,t,s){const i=()=>{if(!this.wavesurfer)return;const r=this.wavesurfer.getWidth(),n=this.wavesurfer.getScroll(),o=t.clientWidth,l=this.wavesurfer.getDuration(),c=Math.round(e.start/l*o),h=c+(Math.round((e.end-e.start)/l*o)||1)>
1n&&c<n+r;h&&!s.parentElement?t.appendChild(s):!h&&s.parentElement&&s.remove()};setTimeout((()=>{if(!this.wavesurfer||!e.element)return;i();const r=this.wavesurfer.on("scroll",i),n=this.wavesurfer.on("zoom",i);this.subscriptions.push(r,n),e.once("remove",(()=>{r(),n()}))}),0)}saveRegion(e){if(!e.element)return;this.virtualAppend(e,this.regionsContainer,e.element),this.avoidOverlapping(e),this.regions.push(e);const t=[e.on("update",(s=>{s||this.adjustScroll(e),this.emit("region-update",e,s)})),e.on("update-end",(s=>{this.avoidOverlapping(e),this.emit("region-updated",e,s)})),e.on("play",(s=>{var i;(i=this.wavesurfer)===null||i===void 0||i.play(e.start,s)})),e.on("click",(s=>{this.emit("region-clicked",e,s)})),e.on("dblclick",(s=>{this.emit("region-double-clicked",e,s)})),e.on("content-changed",(()=>{this.emit("region-content-changed",e)})),e.once("remove",(()=>{t.forEach((s=>s())),this.regions=this.regions.filter((s=>s!==e)),this.emit("region-removed",e)}))];this.subscriptions.push(...t),this.emit("region-created",e)}addRegion(e){var t,s;if(!this.wavesurfer)throw Error("WaveSurfer is not initialized");const i=this.wavesurfer.getDuration(),r=(s=(t=this.wavesurfer)===null||t===void 0?void 0:t.getDecodedData())===null||s===void 0?void 0:s.numberOfChannels,n=new Di(e,i,r);return this.emit("region-initialized",n),i?this.saveRegion(n):this.subscriptions.push(this.wavesurfer.once("ready",(o=>{n._setTotalDuration(o),this.saveRegion(n)}))),n}enableDragSelection(e,t=3){var s;const i=(s=this.wavesurfer)===null||s===void 0?void 0:s.getWrapper();if(!(i&&i instanceof HTMLElement))return()=>{};let r=null,n=0,o=0;return qt(i,((l,c,h)=>{r&&r._onUpdate(l,h>n?"end":"start",o)}),(l=>{var c,h;if(n=l,!this.wavesurfer)return;const u=this.wavesurfer.getDuration(),d=(h=(c=this.wavesurfer)===null||c===void 0?void 0:c.getDecodedData())===null||h===void 0?void 0:h.numberOfChannels,{width:g}=this.wavesurfer.getWrapper().getBoundingClientRect();o=n/g*u;const f=l/g*u,m=(l+5)/g*u;r=new Di(Object.assign(Object.assign({},e),{start:f,end:m}),u,d),this.emit("region-initialized",r),r.element&&this.regionsContainer.appendChild(r.element)}),(()=>{r&&(this.saveRegion(r),r.updatingSide=void 0,r=null)}),t)}clearRegions(){this.regions.slice().forEach((e=>e.remove())),this.regions=[]}destroy(){this.clearRegions(),super.destroy(),this.regionsContainer.remove()}}var Sa=Oe('<input id="volume" class="volume-slider svelte-c0ird4" type="range" min="0" max="1" step="0.01"/>');function La(a,e){ms(e,!0);let t=se(e,"currentVolume",15),s=se(e,"show_volume_slider",15),i;oi(()=>{r()});const r=()=>{let o=i;o&&(o.style.background=`linear-gradient(to right, var(--color-accent) ${(t()??1)*100}%, var(--neutral-400) ${(t()??1)*100}%)`)};Ke(()=>{t(),r()});var n=Sa();Xn(n),n.__focusout=()=>s(!1),n.__input=o=>{o.target instanceof HTMLInputElement&&(t(parseFloat(o.target.value)),e.waveform?.setVolume(t()))},ht(n,o=>i=o,()=>i),xt(()=>Qn(n,t()??1)),Se(a,n),ps()}kr(["focusout","input"]);var Aa=Oe('<button class="action icon cc-button svelte-72dh9g" data-testid="subtitles-toggle"><!></button>'),Ra=Oe('<button class="action icon svelte-72dh9g" aria-label="Reset audio"><!></button>'),ba=Oe('<button class="action icon svelte-72dh9g" aria-label="Trim audio to selection"><!></button>'),Ia=Oe('<button class="text-button svelte-72dh9g">Trim</button> <button class="text-button svelte-72dh9g">Cancel</button>',1),Da=Oe("<!> <!>",1),Ca=Oe('<div class="controls svelte-72dh9g" data-testid="waveform-controls"><div class="control-wrapper svelte-72dh9g"><button class="action icon volume svelte-72dh9g" aria-label="Adjust volume"><!></button> <!> <button><span> </span></button></div> <div class="play-pause-wrapper svelte-72dh9g"><button class="rewind icon svelte-72dh9g"><!></button> <button class="play-pause-button icon svelte-72dh9g"><!></button> <button class="skip icon svelte-72dh9g"><!></button></div> <div class="settings-wrapper svelte-72dh9g"><!> <!></div></div>');function _a(a,e){ms(e,!0);let t=se(e,"show_redo",3,!1),s=se(e,"interactive",3,!1),i=se(e,"mode",15),r=se(e,"waveform_options",19,()=>({})),n=se(e,"trim_region_settings",19,()=>({})),o=se(e,"show_volume_slider",15),l=se(e,"editable",3,!0),c=se(e,"subtitles_toggle",15),h=se(e,"show_subtitles",3,!1),u=se(e,"trimDuration",15),d=[.5,1,1.5,2],g=_e(Zn(d[1])),f=_e(null),m=_e(null),E=_e(null),T=_e(null),y=_e(""),v=_e(1);function A(){e.container&&e.waveform&&!P(f)&&ge(f,e.waveform.registerPlugin(li.create()),!0)}oi(()=>{A()}),Ke(()=>{if(!P(f))return;const z=J=>{J.play()};return P(f).on("region-out",z),()=>{P(f)?.un("region-out",z)}}),Ke(()=>{if(!P(f))return;const z=J=>{u(J.end-J.start)};return P(f).on("region-updated",z),()=>{P(f)?.un("region-updated",z)}}),Ke(()=>{if(!P(f))return;const z=(J,he)=>{he.stopPropagation(),ge(m,J,!0),J.play()};return P(f).on("region-clicked",z),()=>{P(f)?.un("region-clicked",z)}});const x=()=>{P(f)&&(ge(m,P(f)?.addRegion({start:e.audio_duration/4,end:e.audio_duration/2,...n()}),!0),u(P(m).end-P(m).start))};Ke(()=>{if(P(m)){const z=e.container.children[0].shadowRoot;ge(T,z.querySelector('[data-resize="right"]'),!0),ge(E,z.querySelector('[data-resize="left"]'),!0),P(E)&&P(T)&&(P(E).setAttribute("role","button"),P(T).setAttribute("role","button"),P(E)?.setAttribute("aria-label","Drag to adjust start time"),P(T)?.setAttribute("aria-label","Drag to adjust end time"),P(E)?.setAttribute("tabindex","0"),P(T)?.setAttribute("tabindex","0"),P(E).addEventListener("focus",()=>{P(f)&&ge(y,"left")}),P(T).addEventListener("focus",()=>{P(f)&&ge(y,"right")}))}});const D=()=>
1{if(e.waveform&&P(f)&&P(m)){const z=P(m).start,J=P(m).end;e.handle_trim_audio(z,J),i(""),ge(m,null)}},R=()=>{P(f)?.getRegions().forEach(z=>{z.remove()}),P(f)?.clearRegions()},C=()=>{R(),i()?i(""):(i("edit"),A(),x())},k=()=>{c(!c())},I=(z,J)=>{let he,Ue;P(m)&&(z==="left"?J==="ArrowLeft"?(he=P(m).start-.05,Ue=P(m).end):(he=P(m).start+.05,Ue=P(m).end):J==="ArrowLeft"?(he=P(m).start,Ue=P(m).end-.05):(he=P(m).start,Ue=P(m).end+.05),P(m).setOptions({start:he,end:Ue}),u(P(m).end-P(m).start))};Ke(()=>{if(P(f)){const z=J=>{J.key==="ArrowLeft"?I(P(y),"ArrowLeft"):J.key==="ArrowRight"&&I(P(y),"ArrowRight")};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}}});var w=Ca(),B=Te(w),F=Te(B);F.__click=()=>o(!o());let G;var V=Te(F);ha(V,{get currentVolume(){return P(v)}}),ye(F);var U=ve(F,2);{var Z=z=>{La(z,{get waveform(){return e.waveform},get currentVolume(){return P(v)},set currentVolume(J){ge(v,J,!0)},get show_volume_slider(){return o()},set show_volume_slider(J){o(J)}})};Fe(U,z=>{o()&&z(Z)})}var q=ve(U,2);let O;q.__click=()=>{ge(g,d[(d.indexOf(P(g))+1)%d.length],!0),e.waveform?.setPlaybackRate(P(g))};var M=Te(q),ee=Te(M);ye(M),ye(q),ye(B);var j=ve(B,2),X=Te(j);X.__click=()=>e.waveform?.skip(Nt(e.audio_duration,r().skip_length)*-1);var ae=Te(X);pa(ae),ye(X);var re=ve(X,2);re.__click=()=>e.waveform?.playPause();var de=Te(re);{var Re=z=>{ua(z)},Y=z=>{fa(z)};Fe(de,z=>{e.playing?z(Re):z(Y,!1)})}ye(re);var $=ve(re,2);$.__click=()=>e.waveform?.skip(Nt(e.audio_duration,r().skip_length));var fe=Te($);va(fe),ye($),ye(j);var oe=ve(j,2),be=Te(oe);{var Me=z=>{var J=Aa();J.__click=k;var he=Te(J);Ta(he),ye(J),xt(()=>Hs(J,`color: ${c()?"var(--color-accent)":"var(--neutral-400)"}`)),Se(z,J)};Fe(be,z=>{h()&&z(Me)})}var Ne=ve(be,2);{var et=z=>{var J=Da(),he=lt(J);{var Ue=ke=>{var De=Ra();De.__click=()=>{e.handle_reset_value(),R(),i("")};var ue=Te(De);ga(ue),ye(De),Se(ke,De)};Fe(he,ke=>{t()&&!i()&&ke(Ue)})}var Ot=ve(he,2);{var ys=ke=>{var De=ba();De.__click=C;var ue=Te(De);da(ue),ye(De),Se(ke,De)},vs=ke=>{var De=Ia(),ue=lt(De);ue.__click=D;var Pe=ve(ue,2);Pe.__click=C,Se(ke,De)};Fe(Ot,ke=>{i()?ke(vs,!1):ke(ys)})}Se(z,J)};Fe(Ne,z=>{l()&&s()&&z(et)})}ye(oe),ye(w),xt((z,J,he,Ue)=>{G=Hs(F,"",G,{color:o()?"var(--color-accent)":"var(--neutral-400)"}),O=wr(q,1,"playback icon svelte-72dh9g",null,O,{hidden:o()}),Ct(q,"aria-label",z),Pr(ee,`${P(g)??""}x`),Ct(X,"aria-label",J),Ct(re,"aria-label",he),Ct($,"aria-label",`Skip forward by ${Ue??""} seconds`)},[()=>`Adjust playback speed to ${d[(d.indexOf(P(g))+1)%d.length]}x`,()=>`Skip backwards by ${Nt(e.audio_duration,r().skip_length)} seconds`,()=>e.playing?e.i18n("audio.pause"):e.i18n("audio.play"),()=>Nt(e.audio_duration,r().skip_length)]),Se(a,w),ps()}kr(["click"]);function wa(a){return a&&a.__esModule&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a}var Ur={exports:{}};(function(a,e){(function(t){var s=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,r=/(?:\/|^)\.(?=\/)/g,n=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,c,h){if(h=h||{},l=l.trim(),c=c.trim(),!c){if(!h.alwaysNormalize)return l;var u=o.parseURL(l);if(!u)throw new Error("Error trying to parse base URL.");return u.path=o.normalizePath(u.path),o.buildURLFromParts(u)}var d=o.parseURL(c);if(!d)throw new Error("Error trying to parse relative URL.");if(d.scheme)return h.alwaysNormalize?(d.path=o.normalizePath(d.path),o.buildURLFromParts(d)):c;var g=o.parseURL(l);if(!g)throw new Error("Error trying to parse base URL.");if(!g.netLoc&&g.path&&g.path[0]!=="/"){var f=i.exec(g.path);g.netLoc=f[1],g.path=f[2]}g.netLoc&&!g.path&&(g.path="/");var m={scheme:g.scheme,netLoc:d.netLoc,path:null,params:d.params,query:d.query,fragment:d.fragment};if(!d.netLoc&&(m.netLoc=g.netLoc,d.path[0]!=="/"))if(!d.path)m.path=g.path,d.params||(m.params=g.params,d.query||(m.query=g.query));else{var E=g.path,T=E.substring(0,E.lastIndexOf("/")+1)+d.path;m.path=o.normalizePath(T)}return m.path===null&&(m.path=h.alwaysNormalize?o.normalizePath(d.path):d.path),o.buildURLFromParts(m)},parseURL:function(l){var c=s.exec(l);return c?{scheme:c[1]||"",netLoc:c[2]||"",path:c[3]||"",params:c[4]||"",query:c[5]||"",fragment:c[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(r,"");l.length!==(l=l.replace(n,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};a.exports=o})()})(Ur);var ci=Ur.exports;function Ci(a,e){var t=Object.keys(a);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(a);e&&(s=s.filter(function(i){return Object.getOwnPropertyDescriptor(a,i).enumerable})),t.push.apply(t,s)}return t}function Le(a){for(var e=1;e<arguments.length;e++){var t=arguments[e]!=null?arguments[e]:{};
1e%2?Ci(Object(t),!0).forEach(function(s){Fa(a,s,t[s])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(t)):Ci(Object(t)).forEach(function(s){Object.defineProperty(a,s,Object.getOwnPropertyDescriptor(t,s))})}return a}function ka(a,e){if(typeof a!="object"||!a)return a;var t=a[Symbol.toPrimitive];if(t!==void 0){var s=t.call(a,e);if(typeof s!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(a)}function Pa(a){var e=ka(a,"string");return typeof e=="symbol"?e:String(e)}function Fa(a,e,t){return e=Pa(e),e in a?Object.defineProperty(a,e,{value:t,enumerable:!0,configurable:!0,writable:!0}):a[e]=t,a}function me(){return me=Object.assign?Object.assign.bind():function(a){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&(a[s]=t[s])}return a},me.apply(this,arguments)}const N=Number.isFinite||function(a){return typeof a=="number"&&isFinite(a)},Oa=Number.isSafeInteger||function(a){return typeof a=="number"&&Math.abs(a)<=Ma},Ma=Number.MAX_SAFE_INTEGER||9007199254740991;let p=(function(a){return a.MEDIA_ATTACHING="hlsMediaAttaching",a.MEDIA_ATTACHED="hlsMediaAttached",a.MEDIA_DETACHING="hlsMediaDetaching",a.MEDIA_DETACHED="hlsMediaDetached",a.BUFFER_RESET="hlsBufferReset",a.BUFFER_CODECS="hlsBufferCodecs",a.BUFFER_CREATED="hlsBufferCreated",a.BUFFER_APPENDING="hlsBufferAppending",a.BUFFER_APPENDED="hlsBufferAppended",a.BUFFER_EOS="hlsBufferEos",a.BUFFER_FLUSHING="hlsBufferFlushing",a.BUFFER_FLUSHED="hlsBufferFlushed",a.MANIFEST_LOADING="hlsManifestLoading",a.MANIFEST_LOADED="hlsManifestLoaded",a.MANIFEST_PARSED="hlsManifestParsed",a.LEVEL_SWITCHING="hlsLevelSwitching",a.LEVEL_SWITCHED="hlsLevelSwitched",a.LEVEL_LOADING="hlsLevelLoading",a.LEVEL_LOADED="hlsLevelLoaded",a.LEVEL_UPDATED="hlsLevelUpdated",a.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",a.LEVELS_UPDATED="hlsLevelsUpdated",a.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",a.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",a.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",a.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",a.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",a.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",a.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",a.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",a.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",a.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",a.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",a.CUES_PARSED="hlsCuesParsed",a.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",a.INIT_PTS_FOUND="hlsInitPtsFound",a.FRAG_LOADING="hlsFragLoading",a.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",a.FRAG_LOADED="hlsFragLoaded",a.FRAG_DECRYPTED="hlsFragDecrypted",a.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",a.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",a.FRAG_PARSING_METADATA="hlsFragParsingMetadata",a.FRAG_PARSED="hlsFragParsed",a.FRAG_BUFFERED="hlsFragBuffered",a.FRAG_CHANGED="hlsFragChanged",a.FPS_DROP="hlsFpsDrop",a.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",a.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",a.ERROR="hlsError",a.DESTROYING="hlsDestroying",a.KEY_LOADING="hlsKeyLoading",a.KEY_LOADED="hlsKeyLoaded",a.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",a.BACK_BUFFER_REACHED="hlsBackBufferReached",a.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",a})({}),W=(function(a){return a.NETWORK_ERROR="networkError",a.MEDIA_ERROR="mediaError",a.KEY_SYSTEM_ERROR="keySystemError",a.MUX_ERROR="muxError",a.OTHER_ERROR="otherError",a})({}),b=(function(a){return a.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",a.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",a.KEY_SYSTEM_NO_SESSION="keySystemNoSession",a.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",a.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",a.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",a.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",a.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",a.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",a.MANIFEST_LOAD_ERROR="manifestLoadError",a.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",a.MANIFEST_PARSING_ERROR="manifestParsingError",a.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",a.LEVEL_EMPTY_ERROR="levelEmptyError",a.LEVEL_LOAD_ERROR="levelLoadError",a.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",a.LEVEL_PARSING_ERROR="levelParsingError",a.LEVEL_SWITCH_ERROR="levelSwitchError",a.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",a.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",a.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",a.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",a.FRAG_LOAD_ERROR="fragLoadError",a.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",a.FRAG_DECRYPT_ERROR="fragDecryptError",a.FRAG_PARSING_ERROR="fragParsingError",a.FRAG_GAP="fragGap",a.REMUX_ALLOC_ER
vendor: 11,765 bytes, line 1
1ROR="remuxAllocError",a.KEY_LOAD_ERROR="keyLoadError",a.KEY_LOAD_TIMEOUT="keyLoadTimeOut",a.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",a.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",a.BUFFER_APPEND_ERROR="bufferAppendError",a.BUFFER_APPENDING_ERROR="bufferAppendingError",a.BUFFER_STALLED_ERROR="bufferStalledError",a.BUFFER_FULL_ERROR="bufferFullError",a.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",a.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",a.INTERNAL_EXCEPTION="internalException",a.INTERNAL_ABORTED="aborted",a.UNKNOWN="unknown",a})({});const ut=function(){},Ws={trace:ut,debug:ut,log:ut,warn:ut,info:ut,error:ut};let wt=Ws;function Na(a){const e=self.console[a];return e?e.bind(self.console,`[${a}] >`):ut}function Ua(a,...e){e.forEach(function(t){wt[t]=a[t]?a[t].bind(a):Na(t)})}function Ba(a,e){if(typeof console=="object"&&a===!0||typeof a=="object"){Ua(a,"debug","log","info","warn","error");try{wt.log(`Debug logs enabled for "${e}" in hls.js version 1.5.13`)}catch{wt=Ws}}else wt=Ws}const S=wt,Ga=/^(\d+)x(\d+)$/,_i=/(.+?)=(".*?"|.*?)(?:,|$)/g;class ce{constructor(e){typeof e=="string"&&(e=ce.parseAttrList(e)),me(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const t=parseInt(this[e],10);return t>Number.MAX_SAFE_INTEGER?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||"0x").slice(2);t=(t.length&1?"0":"")+t;const s=new Uint8Array(t.length/2);for(let i=0;i<t.length/2;i++)s[i]=parseInt(t.slice(i*2,i*2+2),16);return s}else return null}hexadecimalIntegerAsNumber(e){const t=parseInt(this[e],16);return t>Number.MAX_SAFE_INTEGER?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){const s=this[e];return s?parseFloat(s):t}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const t=Ga.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e){let t;const s={};for(_i.lastIndex=0;(t=_i.exec(e))!==null;){let r=t[2];r.indexOf('"')===0&&r.lastIndexOf('"')===r.length-1&&(r=r.slice(1,-1));const n=t[1].trim();s[n]=r}return s}}function $a(a){return a!=="ID"&&a!=="CLASS"&&a!=="START-DATE"&&a!=="DURATION"&&a!=="END-DATE"&&a!=="END-ON-NEXT"}function Ka(a){return a==="SCTE35-OUT"||a==="SCTE35-IN"}class Br{constructor(e,t){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,t){const s=t.attr;for(const i in s)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==s[i]){S.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=me(new ce({}),s,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=new Date(this.attr["END-DATE"]);N(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(N(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isValid(){return!!this.id&&!this._badValueForSameId&&N(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Es{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var ie={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class Gr{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[ie.AUDIO]:null,[ie.VIDEO]:null,[ie.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,t){const s=e.split("@",2);let i;s.length===1?i=t?.byteRangeEndOffset||0:i=parseInt(s[1]),this._byteRange=[i,parseInt(s[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=ci.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class Ss extends Gr{constructor(e,t){super(t),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Es,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{const s=Object.keys(this.levelkeys);if(s.length===1)return this._decryptdata=this.levelkeys[s[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!N(this.programDateTime))return null;const e=N(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){const t=Object.keys(this.levelkeys),s=t.length;if(s>1||s===1&&this.levelkeys[t[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const t=this.levelkeys[e];t&&!this._decryptdata&&(this._decryptdata=t.getDecryptData(this.sn))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,s,i,r,n=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:t,endPTS:s,startDTS:i,endDTS:r,partial:n};return}l.startPTS=Math.min(l.startPTS,t),l.endPTS=Math.max(l.endPTS,s),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,r)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[ie.AUDIO]=null,e[ie.VIDEO]=null,e[ie.AUDIOVIDEO]=null}}class Ha extends Gr{constructor(e,t,s,i,r){super(s),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Es,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=i;const n=e.enumeratedString("BYTERANGE");n&&this.setByteRange(n,r),r&&(this.fragOffset=r.fragOffset+r.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}}const Va=10;class Wa{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,s=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!s||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&s>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?N(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Va}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function hi(a){return Uint8Array.from(atob(a),e=>e.charCodeAt(0))}function Ya(a){const e=Ys(a).subarray(0,16),t=new Uint8Array(16);return t.set(e,16-e.length),t}function ja(a){const e=function(s,i,r){const n=s[i];s[i]=s[r],s[r]=n};e(a,0,3),e(a,1,2),e(a,4,5),e(a,6,7)}function za(a){const e=a.split(":");let t=null;if(e[0]==="data"&&e.length===2){const s=e[1].split(";"),i=s[s.length-1].split(",");if(i.length===2){const r=i[0]==="base64",n=i[1];r?(s.splice(-1,1),t=hi(n)):t=Ya(n)}}return t}function Ys(a){return Uint8Array.from(unescape(encodeURIComponent(a)),e=>e.charCodeAt(0))}const At=typeof self<"u"?self:void 0;var le={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},we={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function wi(a){switch(a){case we.FAIRPLAY:return le.FAIRPLAY;case we.PLAYREADY:return le.PLAYREADY;case we.WIDEVINE:return le.WIDEVINE;case we.CLEARKEY:return le.CLEARKEY}}var $r={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function qa(a){if(a===$r.WIDEVINE)return le.WIDEVINE}function ki(a){switch(a){case le.FAIRPLAY:return we.FAIRPLAY;case le.PLAYREADY:return we.PLAYREADY;case le.WIDEVINE:return we.WIDEVINE;case le.CLEARKEY:return we.CLEARKEY}}function Ls(a){const{drmSystems:e,widevineLicenseUrl:t}=a,s=e?[le.FAIRPLAY,le.WIDEVINE,le.PLAYREADY,le.CLEARKEY].filter(i=>!!e[i]):[];return!s[le.WIDEVINE]&&t&&s.push(le.WIDEVINE),s}const Kr=(function(a){return At!=null&&(a=At.navigator)!=null&&a.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function Xa(a,e,t,s){let i;switch(a){case le.FAIRPLAY:i=["cenc","sinf"];break;case le.WIDEVINE:case le.PLAYREADY:i=["cenc"];break;case le.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${a}`)}return Qa(i,e,t,s)}function Qa(a,e,t,s){return[{initDataTypes:a,persistentState:s.persistentState||"optional",distinctiveIdentifier:s.distinctiveIdentifier||"optional",sessionTypes:s.sessionTypes||[s.sessionType||"temporary"],audioCapabilities:e.map(r=>({contentType:`audio/mp4; codecs="${r}
1"`,robustness:s.audioRobustness||"",encryptionScheme:s.audioEncryptionScheme||null})),videoCapabilities:t.map(r=>({contentType:`video/mp4; codecs="${r}"`,robustness:s.videoRobustness||"",encryptionScheme:s.videoEncryptionScheme||null}))}]}function ft(a,e,t){return Uint8Array.prototype.slice?a.slice(e,t):new Uint8Array(Array.prototype.slice.call(a,e,t))}const ui=(a,e)=>e+10<=a.length&&a[e]===73&&a[e+1]===68&&a[e+2]===51&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,Hr=(a,e)=>e+10<=a.length&&a[e]===51&&a[e+1]===68&&a[e+2]===73&&a[e+3]<255&&a[e+4]<255&&a[e+6]<128&&a[e+7]<128&&a[e+8]<128&&a[e+9]<128,kt=(a,e)=>{const t=e;let s=0;for(;ui(a,e);){s+=10;const i=Ts(a,e+6);s+=i,Hr(a,e+10)&&(s+=10),e+=s}if(s>0)return a.subarray(t,t+s)},Ts=(a,e)=>{let t=0;return t=(a[e]&127)<<21,t|=(a[e+1]&127)<<14,t|=(a[e+2]&127)<<7,t|=a[e+3]&127,t},Ja=(a,e)=>ui(a,e)&&Ts(a,e+6)+10<=a.length-e,di=a=>{const e=Wr(a);for(let t=0;t<e.length;t++){const s=e[t];if(Vr(s))return ro(s)}},Vr=a=>a&&a.key==="PRIV"&&a.info==="com.apple.streaming.transportStreamTimestamp",Za=a=>{const e=String.fromCharCode(a[0],a[1],a[2],a[3]),t=Ts(a,4),s=10;return{type:e,size:t,data:a.subarray(s,s+t)}},Wr=a=>{let e=0;const t=[];for(;ui(a,e);){const s=Ts(a,e+6);e+=10;const i=e+s;for(;e+8<i;){const r=Za(a.subarray(e)),n=eo(r);n&&t.push(n),e+=r.size+10}Hr(a,e)&&(e+=10)}return t},eo=a=>a.type==="PRIV"?to(a):a.type[0]==="W"?io(a):so(a),to=a=>{if(a.size<2)return;const e=Je(a.data,!0),t=new Uint8Array(a.data.subarray(e.length+1));return{key:a.type,info:e,data:t.buffer}},so=a=>{if(a.size<2)return;if(a.type==="TXXX"){let t=1;const s=Je(a.data.subarray(t),!0);t+=s.length+1;const i=Je(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Je(a.data.subarray(1));return{key:a.type,data:e}},io=a=>{if(a.type==="WXXX"){if(a.size<2)return;let t=1;const s=Je(a.data.subarray(t),!0);t+=s.length+1;const i=Je(a.data.subarray(t));return{key:a.type,info:s,data:i}}const e=Je(a.data);return{key:a.type,data:e}},ro=a=>{if(a.data.byteLength===8){const e=new Uint8Array(a.data),t=e[3]&1;let s=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return s/=45,t&&(s+=4772185884e-2),Math.round(s)}},Je=(a,e=!1)=>{const t=no();if(t){const c=t.decode(a);if(e){const h=c.indexOf("\0");return h!==-1?c.substring(0,h):c}return c.replace(/\0/g,"")}const s=a.length;let i,r,n,o="",l=0;for(;l<s;){if(i=a[l++],i===0&&e)return o;if(i===0||i===3)continue;switch(i>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:r=a[l++],o+=String.fromCharCode((i&31)<<6|r&63);break;case 14:r=a[l++],n=a[l++],o+=String.fromCharCode((i&15)<<12|(r&63)<<6|(n&63)<<0);break}}return o};let As;function no(){if(!navigator.userAgent.includes("PlayStation 4"))return!As&&typeof self.TextDecoder<"u"&&(As=new self.TextDecoder("utf-8")),As}const ze={hexDump:function(a){let e="";for(let t=0;t<a.length;t++){let s=a[t].toString(16);s.length<2&&(s="0"+s),e+=s}return e}},rs=Math.pow(2,32)-1,ao=[].push,Yr={video:1,audio:2,id3:3,text:4};function pe(a){return String.fromCharCode.apply(null,a)}function jr(a,e){const t=a[e]<<8|a[e+1];return t<0?65536+t:t}function K(a,e){const t=zr(a,e);return t<0?4294967296+t:t}function Pi(a,e){let t=K(a,e);return t*=Math.pow(2,32),t+=K(a,e+4),t}function zr(a,e){return a[e]<<24|a[e+1]<<16|a[e+2]<<8|a[e+3]}function Rs(a,e,t){a[e]=t>>24,a[e+1]=t>>16&255,a[e+2]=t>>8&255,a[e+3]=t&255}function oo(a){const e=a.byteLength;for(let t=0;t<e;){const s=K(a,t);if(s>8&&a[t+4]===109&&a[t+5]===111&&a[t+6]===111&&a[t+7]===102)return!0;t=s>1?t+s:e}return!1}function Q(a,e){const t=[];if(!e.length)return t;const s=a.byteLength;for(let i=0;i<s;){const r=K(a,i),n=pe(a.subarray(i+4,i+8)),o=r>1?i+r:s;if(n===e[0])if(e.length===1)t.push(a.subarray(i+8,o));else{const l=Q(a.subarray(i+8,o),e.slice(1));l.length&&ao.apply(t,l)}i=o}return t}function lo(a){const e=[],t=a[0];let s=8;const i=K(a,s);s+=4;let r=0,n=0;t===0?(r=K(a,s),n=K(a,s+4),s+=8):(r=Pi(a,s),n=Pi(a,s+8),s+=16),s+=2;let o=a.length+n;const l=jr(a,s);s+=2;for(let c=0;c<l;c++){let h=s;const u=K(a,h);h+=4;const d=u&2147483647;if((u&2147483648)>>>31===1)return S.warn("SIDX has hierarchical references (not supported)"),null;const f=K(a,h);h+=4,e.push({referenceSize:d,subsegmentDuration:f,info:{duration:f/i,start:o,end:o+d-1}}),o+=d,h+=4,s=h}return{earliestPresentationTime:r,timescale:i,version:t,referencesCount:l,references:e}}
vendor: 56,904 bytes, line 1
1function qr(a){const e=[],t=Q(a,["moov","trak"]);for(let i=0;i<t.length;i++){const r=t[i],n=Q(r,["tkhd"])[0];if(n){let o=n[0];const l=K(n,o===0?12:20),c=Q(r,["mdia","mdhd"])[0];if(c){o=c[0];const h=K(c,o===0?12:20),u=Q(r,["mdia","hdlr"])[0];if(u){const d=pe(u.subarray(8,12)),g={soun:ie.AUDIO,vide:ie.VIDEO}[d];if(g){const f=Q(r,["mdia","minf","stbl","stsd"])[0],m=co(f);e[l]={timescale:h,type:g},e[g]=Le({timescale:h,id:l},m)}}}}}return Q(a,["moov","mvex","trex"]).forEach(i=>{const r=K(i,4),n=e[r];n&&(n.default={duration:K(i,12),flags:K(i,20)})}),e}function co(a){const e=a.subarray(8),t=e.subarray(86),s=pe(e.subarray(4,8));let i=s;const r=s==="enca"||s==="encv";if(r){const o=Q(e,[s])[0].subarray(s==="enca"?28:78);Q(o,["sinf"]).forEach(c=>{const h=Q(c,["schm"])[0];if(h){const u=pe(h.subarray(4,8));if(u==="cbcs"||u==="cenc"){const d=Q(c,["frma"])[0];d&&(i=pe(d))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const n=Q(t,["avcC"])[0];i+="."+Ut(n[1])+Ut(n[2])+Ut(n[3]);break}case"mp4a":{const n=Q(e,[s])[0],o=Q(n.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=bs(o,l),l+=2;const c=o[l++];if(c&128&&(l+=2),c&64&&(l+=o[l++]),o[l++]!==4)break;l=bs(o,l);const h=o[l++];if(h===64)i+="."+Ut(h);else break;if(l+=12,o[l++]!==5)break;l=bs(o,l);const u=o[l++];let d=(u&248)>>3;d===31&&(d+=1+((u&7)<<3)+((o[l]&224)>>5)),i+="."+d}break}case"hvc1":case"hev1":{const n=Q(t,["hvcC"])[0],o=n[1],l=["","A","B","C"][o>>6],c=o&31,h=K(n,2),u=(o&32)>>5?"H":"L",d=n[12],g=n.subarray(6,12);i+="."+l+c,i+="."+h.toString(16).toUpperCase(),i+="."+u+d;let f="";for(let m=g.length;m--;){const E=g[m];(E||f)&&(f="."+E.toString(16).toUpperCase()+f)}i+=f;break}case"dvh1":case"dvhe":{const n=Q(t,["dvcC"])[0],o=n[2]>>1&127,l=n[2]<<5&32|n[3]>>3&31;i+="."+je(o)+"."+je(l);break}case"vp09":{const n=Q(t,["vpcC"])[0],o=n[4],l=n[5],c=n[6]>>4&15;i+="."+je(o)+"."+je(l)+"."+je(c);break}case"av01":{const n=Q(t,["av1C"])[0],o=n[1]>>>5,l=n[1]&31,c=n[2]>>>7?"H":"M",h=(n[2]&64)>>6,u=(n[2]&32)>>5,d=o===2&&h?u?12:10:h?10:8,g=(n[2]&16)>>4,f=(n[2]&8)>>3,m=(n[2]&4)>>2,E=n[2]&3;i+="."+o+"."+je(l)+c+"."+je(d)+"."+g+"."+f+m+E+"."+je(1)+"."+je(1)+"."+je(1)+"."+0;break}}return{codec:i,encrypted:r}}function bs(a,e){const t=e+5;for(;a[e++]&128&&e<t;);return e}function Ut(a){return("0"+a.toString(16).toUpperCase()).slice(-2)}function je(a){return(a<10?"0":"")+a}function ho(a,e){if(!a||!e)return a;const t=e.keyId;return t&&e.isCommonEncryption&&Q(a,["moov","trak"]).forEach(i=>{const n=Q(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Q(n,["enca"]);const l=o.length>0;l||(o=Q(n,["encv"])),o.forEach(c=>{const h=l?c.subarray(28):c.subarray(78);Q(h,["sinf"]).forEach(d=>{const g=Xr(d);if(g){const f=g.subarray(8,24);f.some(m=>m!==0)||(S.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${ze.hexDump(f)} -> ${ze.hexDump(t)}`),g.set(t,8))}})})}),a}function Xr(a){const e=Q(a,["schm"])[0];if(e){const t=pe(e.subarray(4,8));if(t==="cbcs"||t==="cenc")return Q(a,["schi","tenc"])[0]}return S.error("[eme] missing 'schm' box"),null}function uo(a,e){return Q(e,["moof","traf"]).reduce((t,s)=>{const i=Q(s,["tfdt"])[0],r=i[0],n=Q(s,["tfhd"]).reduce((o,l)=>{const c=K(l,4),h=a[c];if(h){let u=K(i,4);if(r===1){if(u===rs)return S.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;u*=rs+1,u+=K(i,8)}const d=h.timescale||9e4,g=u/d;if(N(g)&&(o===null||g<o))return g}return o},null);return n!==null&&N(n)&&(t===null||n<t)?n:t},null)}function fo(a,e){let t=0,s=0,i=0;const r=Q(a,["moof","traf"]);for(let n=0;n<r.length;n++){const o=r[n],l=Q(o,["tfhd"])[0],c=K(l,4),h=e[c];if(!h)continue;const u=h.default,d=K(l,0)|u?.flags;let g=u?.duration;d&8&&(d&2?g=K(l,12):g=K(l,8));const f=h.timescale||9e4,m=Q(o,["trun"]);for(let E=0;E<m.length;E++){if(t=go(m[E]),!t&&g){const T=K(m[E],4);t=g*T}h.type===ie.VIDEO?s+=t/f:h.type===ie.AUDIO&&(i+=t/f)}}if(s===0&&i===0){let n=1/0,o=0,l=0;const c=Q(a,["sidx"]);for(let h=0;h<c.length;h++){const u=lo(c[h]);if(u!=null&&u.references){n=Math.min(n,u.earliestPresentationTime/u.timescale);const d=u.references.reduce((g,f)=>g+f.info.duration||0,0);o=Math.max(o,d+u.earliestPresentationTime/u.timescale),l=o-n}}if(l&&N(l))return l}return s||i}function go(a){const e=K(a,0);let t=8;e&1&&(t+=4),e&4&&(t+=4);let s=0;const i=K(a,4);for(let r=0;r<i;r++){if(e&256){const n=K(a,t);s+=n,t+=4}e&512&&(t+=4),e&1024&&(t+=4),e&2048&&(t+=4)}return s}function mo(a,e,t){Q(e,["moof","traf"]).forEach(s=>{Q(s,["tfhd"]).forEach(i=>{const r=K(i,4),n=a[r];if(!n)return;const o=n.timescale||9e4;Q(s,["tfdt"]).forEach(l=>{const c=l[0],h=t*o;if(h){let u=K(l,4);if(c===0)u-=h,u=Math.max(u,0),Rs(l,4,u);else{u*=Math.pow(2,32),u+=K(l,8),u-=h,u=Math.max(u,0);const d=Math.floor(u/(rs+1)),g=Math.floor(u%(rs+1));Rs(l,4,d),Rs(l,8,g)}}})})})}function po(a){const e={valid:null,remainder:null},t=Q(a,["moof"]);if(t.length<2)return e.remainder=a,e;const s=t[t.length-1];return e.valid=ft(a,0,s.byteOffset-8),e.remainder=ft(a,s.byteOffset-8),e}function He(a,e){const t=new Uint8Array(a.length+e.length);return t.set(a),t.set(e,a.length),t}function Fi(a,e){const t=[],s=e.samples,i=e.timescale,r=e.id;let n=!1;return Q(s,["moof"]).map(l=>{const c=l.byteOffset-8;Q(l,["traf"]).map(u=>{const d=Q(u,["tfdt"]).map(g=>{const f=g[0];let m=K(g,4);return f===1&&(m*=Math.pow(2,32),m+=K(g,8)),m/i})[0];return d!==void 0&&(a=d),Q(u,["tfhd"]).map(g=>{const f=K(g,4),m=K(g,0)&16777215,E=(m&1)!==0,T=(m&2)!==0,y=(m&8)!==0;let v=0;const A=(m&16)!==0;let x=0;const D=(m&32)!==0;let R=8;f===r&&(E&&(R+=8),T&&(R+=4),y&&(v=K(g,R),R+=4),A&&(x=K(g,R),R+=4),D&&(R+=4),e.type==="video"&&(n=Eo(e.codec)),Q(u,["trun"]).map(C=>{const k=C[0],I=K(C,0)&16777215,w=(I&1)!==0;let B=0;const F=(I&4)!==0,G=(I&256)!==0;let V=0;const U=(I&512)!==0;let Z=0;const q=(I&1024)!==0,O=(I&2048)!==0;let M=0;const ee=K(C,4);let j=8;w&&(B=K(C,j),j+=4),F&&(j+=4);let X=B+c;for(let ae=0;ae<ee;ae++){if(G?(V=K(C,j),j+=4):V=v,U?(Z=K(C,j),j+=4):Z=x,q&&(j+=4),O&&(k===0?M=K(C,j):M=zr(C,j),j+=4),e.type===ie.VIDEO){let re=0;for(;re<Z;){const de=K(s,X);if(X+=4,To(n,s[X])){const Re=s.subarray(X,X+de);Qr(Re,n?2:1,a+M/i,t)}X+=de,re+=de+4}}a+=V/i}}))})})}),t}function Eo(a){if(!a)return!1;const e=a.indexOf("."),t=e<0?a:a.substring(0,e);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function To(a,e){if(a){const t=e>>1&63;return t===39||t===40}else return(e&31)===6}function Qr(a,e,t,s){const i=Jr(a);let r=0;r+=e;let n=0,o=0,l=0;for(;r<i.length;){n=0;do{if(r>=i.length)break;l=i[r++],n+=l}while(l===255);o=0;do{if(r>=i.length)break;l=i[r++],o+=l}while(l===255);const c=i.length-r;let h=r;if(o<c)r+=o;else if(o>c){S.error(`Malformed SEI payload. ${o} is too small, only ${c} bytes left to parse.`);break}if(n===4){if(i[h++]===181){const d=jr(i,h);if(h+=2,d===49){const g=K(i,h);if(h+=4,g===1195456820){const f=i[h++];if(f===3){const m=i[h++],E=31&m,T=64&m,y=T?2+E*3:0,v=new Uint8Array(y);if(T){v[0]=m;for(let A=1;A<y;A++)v[A]=i[h++]}s.push({type:f,payloadType:n,pts:t,bytes:v})}}}}}else if(n===5&&o>16){const u=[];for(let f=0;f<16;f++){const m=i[h++].toString(16);u.push(m.length==1?"0"+m:m),(f===3||f===5||f===7||f===9)&&u.push("-")}const d=o-16,g=new Uint8Array(d);for(let f=0;f<d;f++)g[f]=i[h++];s.push({payloadType:n,pts:t,uuid:u.join(""),userData:Je(g),userDataBytes:g})}}}function Jr(a){const e=a.byteLength,t=[];let s=1;for(;s<e-2;)a[s]===0&&a[s+1]===0&&a[s+2]===3?(t.push(s+2),s+=2):s++;if(t.length===0)return a;const i=e-t.length,r=new Uint8Array(i);let n=0;for(s=0;s<i;n++,s++)n===t[0]&&(n++,t.shift()),r[s]=a[n];return r}function yo(a){const e=a[0];let t="",s="",i=0,r=0,n=0,o=0,l=0,c=0;if(e===0){for(;pe(a.subarray(c,c+1))!=="\0";)t+=pe(a.subarray(c,c+1)),c+=1;for(t+=pe(a.subarray(c,c+1)),c+=1;pe(a.subarray(c,c+1))!=="\0";)s+=pe(a.subarray(c,c+1)),c+=1;s+=pe(a.subarray(c,c+1)),c+=1,i=K(a,12),r=K(a,16),o=K(a,20),l=K(a,24),c=28}else if(e===1){c+=4,i=K(a,c),c+=4;const u=K(a,c);c+=4;const d=K(a,c);for(c+=4,n=2**32*u+d,Oa(n)||(n=Number.MAX_SAFE_INTEGER,S.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=K(a,c),c+=4,l=K(a,c),c+=4;pe(a.subarray(c,c+1))!=="\0";)t+=pe(a.subarray(c,c+1)),c+=1;for(t+=pe(a.subarray(c,c+1)),c+=1;pe(a.subarray(c,c+1))!=="\0";)s+=pe(a.subarray(c,c+1)),c+=1;s+=pe(a.subarray(c,c+1)),c+=1}const h=a.subarray(c,a.byteLength);return{schemeIdUri:t,value:s,timeScale:i,presentationTime:n,presentationTimeDelta:r,eventDuration:o,id:l,payload:h}}function vo(a,...e){const t=e.length;let s=8,i=t;for(;i--;)s+=e[i].byteLength;const r=new Uint8Array(s);for(r[0]=s>>24&255,r[1]=s>>16&255,r[2]=s>>8&255,r[3]=s&255,r.set(a,4),i=0,s=8;i<t;i++)r.set(e[i],s),s+=e[i].byteLength;return r}function xo(a,e,t){if(a.byteLength!==16)throw new RangeError("Invalid system id");let s,i;s=0,i=new Uint8Array;let r;s>0?(r=new Uint8Array(4),e.length>0&&new DataView(r.buffer).setUint32(0,e.length,!1)):r=new Uint8Array;const n=new Uint8Array(4);return t&&t.byteLength>0&&new DataView(n.buffer).setUint32(0,t.byteLength,!1),vo([112,115,115,104],new Uint8Array([s,0,0,0]),a,r,i,n,t||new Uint8Array)}function So(a){if(!(a instanceof ArrayBuffer)||a.byteLength<32)return null;const e={version:0,systemId:"",kids:null,data:null},t=new DataView(a),s=t.getUint32(0);if(a.byteLength!==s&&s>44||t.getUint32(4)!==1886614376||(e.version=t.getUint32(8)>>>24,e.version>1))return null;e.systemId=ze.hexDump(new Uint8Array(a,12,16));const r=t.getUint32(28);if(e.version===0){if(s-32<r)return null;e.data=new Uint8Array(a,32,r)}else if(e.version===1){e.kids=[];for(let n=0;n<r;n++)e.kids.push(new Uint8Array(a,32+n*16,16))}return e}let Bt={};class Pt{static clearKeyUriToKeyIdMap(){Bt={}}constructor(e,t,s,i=[1],r=null){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=s,this.keyFormatVersions=i,this.iv=r,this.encrypted=e?e!=="NONE":!1,this.isCommonEncryption=this.encrypted&&e!=="AES-128"}isSupported(){if(this.method){if(this.method==="AES-128"||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case we.FAIRPLAY:case we.WIDEVINE:case we.PLAYREADY:case we.CLEARKEY:return["ISO-23001-7","SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(e){if(!this.encrypted||!this.uri)return null;if(this.method==="AES-128"&&this.uri&&!this.iv){typeof e!="number"&&(this.method==="AES-128"&&!this.iv&&S.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),e=0);const s=Lo(e);return new Pt(this.method,this.uri,"identity",this.keyFormatVersions,s)}const t=za(this.uri);if(t)switch(this.keyFormat){case we.WIDEVINE:this.pssh=t,t.length>=22&&(this.keyId=t.subarray(t.length-22,t.length-6));break;case we.PLAYREADY:{const s=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=xo(s,null,t);const i=new Uint16Array(t.buffer,t.byteOffset,t.byteLength/2),r=String.fromCharCode.apply(null,Array.from(i)),n=r.substring(r.indexOf("<"),r.length),c=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(c){const h=c.childNodes[0]?c.childNodes[0].nodeValue:c.getAttribute("VALUE");if(h){const u=hi(h).subarray(0,16);ja(u),this.keyId=u}}break}default:{let s=t.subarray(0,16);if(s.length!==16){const i=new Uint8Array(16);i.set(s,16-s.length),s=i}this.keyId=s;break}}if(!this.keyId||this.keyId.byteLength!==16){let s=Bt[this.uri];if(!s){const i=Object.keys(Bt).length%Number.MAX_SAFE_INTEGER;s=new Uint8Array(16),new DataView(s.buffer,12,4).setUint32(0,i),Bt[this.uri]=s}this.keyId=s}return this}}function Lo(a){const e=new Uint8Array(16);for(let t=12;t<16;t++)e[t]=a>>8*(15-t)&255;return e}const Zr=/\{\$([a-zA-Z0-9-_]+)\}/g;function Oi(a){return Zr.test(a)}function Ce(a,e,t){if(a.variableList!==null||a.hasVariableRefs)for(let s=t.length;s--;){const i=t[s],r=e[i];r&&(e[i]=js(a,r))}}function js(a,e){if(a.variableList!==null||a.hasVariableRefs){const t=a.variableList;return e.replace(Zr,s=>{const i=s.substring(2,s.length-1),r=t?.[i];return r===void 0?(a.playlistParsingError||(a.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),s):r})}return e}function Mi(a,e,t){let s=a.variableList;s||(a.variableList=s={});let i,r;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const n=new self.URL(t).searchParams;if(n.has(i))r=n.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${t}"`)}catch(n){a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${n.message}`))}}else i=e.NAME,r=e.VALUE;i in s?a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):s[i]=r||""}function Ao(a,e,t){const s=e.IMPORT;if(t&&s in t){let i=a.variableList;i||(a.variableList=i={}),i[s]=t[s]}else a.playlistParsingError||(a.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${s}"`))}function gt(a=!0){return typeof self>"u"?void 0:(a||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function Ro(a){return typeof self<"u"&&a===self.ManagedMediaSource}const ns={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function bo(a,e){const t=ns[e];return!!t&&!!t[a.slice(0,4)]}function Is(a,e,t=!0){return!a.split(",").some(s=>!en(s,e,t))}function en(a,e,t=!0){var s;const i=gt(t);return(s=i?.isTypeSupported(Ft(a,e)))!=null?s:!1}function Ft(a,e){return`${e}/mp4;codecs="${a}"`}function Ni(a){if(a){const e=a.substring(0,4);return ns.video[e]}return 2}function as(a){return a.split(",").reduce((e,t)=>{const s=ns.video[t];return s?(s*2+e)/(e?3:2):(ns.audio[t]+e)/(e?2:1)},0)}const Ds={};function Io(a,e=!0){if(Ds[a])return Ds[a];const t={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[a];for(let s=0;s<t.length;s++)if(en(t[s],"audio",e))return Ds[a]=t[s],t[s];return a}const Do=/flac|opus/i;function os(a,e=!0){return a.replace(Do,t=>Io(t.toLowerCase(),e))}function Ui(a,e){return a&&a!=="mp4a"?a:e&&e.split(",")[0]}function Co(a){const e=a.split(",");for(let t=0;t<e.length;t++){const s=e[t].split(".");if(s.length>2){let i=s.shift()+".";i+=parseInt(s.shift()).toString(16),i+=("000"+parseInt(s.shift()).toString(16)).slice(-4),e[t]=i}}return e.join(",")}const Bi=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,Gi=/#EXT-X-MEDIA:(.*)/g,_o=/^#EXT(?:INF|-X-TARGETDURATION):/m,$i=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),wo=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class Xe{static findGroup(e,t){for(let s=0;s<e.length;s++){const i=e[s];if(i.id===t)return i}}static resolve(e,t){return ci.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return _o.test(e)}static parseMasterPlaylist(e,t){const s=Oi(e),i={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:s},r=[];Bi.lastIndex=0;let n;for(;(n=Bi.exec(e))!=null;)if(n[1]){var o;const c=new ce(n[1]);Ce(i,c,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);const h=js(i,n[2]),u={attrs:c,bitrate:c.decimalInteger("BANDWIDTH")||c.decimalInteger("AVERAGE-BANDWIDTH"),name:c.NAME,url:Xe.resolve(h,t)},d=c.decimalResolution("RESOLUTION");d&&(u.width=d.width,u.height=d.height),ko(c.CODECS,u),(o=u.unknownCodecs)!=null&&o.length||r.push(u),i.levels.push(u)}else if(n[3]){const c=n[3],h=n[4];switch(c){case"SESSION-DATA":{const u=new ce(h);Ce(i,u,["DATA-ID","LANGUAGE","VALUE","URI"]);const d=u["DATA-ID"];d&&(i.sessionData===null&&(i.sessionData={}),i.sessionData[d]=u);break}case"SESSION-KEY":{const u=Ki(h,t,i);u.encrypted&&u.isSupported()?(i.sessionKeys===null&&(i.sessionKeys=[]),i.sessionKeys.push(u)):S.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${h}"`);break}case"DEFINE":{{const u=new ce(h);Ce(i,u,["NAME","VALUE","QUERYPARAM"]),Mi(i,u,t)}break}case"CONTENT-STEERING":{const u=new ce(h);Ce(i,u,["SERVER-URI","PATHWAY-ID"]),i.contentSteering={uri:Xe.resolve(u["SERVER-URI"],t),pathwayId:u["PATHWAY-ID"]||"."};break}case"START":{i.startTimeOffset=Hi(h);break}}}const l=r.length>0&&r.length<i.levels.length;return i.levels=l?r:i.levels,i.levels.length===0&&(i.playlistParsingError=new Error("no levels found in manifest")),i}static parseMasterPlaylistMedia(e,t,s){let i;const r={},n=s.levels,o={AUDIO:n.map(c=>({id:c.attrs.AUDIO,audioCodec:c.audioCodec})),SUBTITLES:n.map(c=>({id:c.attrs.SUBTITLES,textCodec:c.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(Gi.lastIndex=0;(i=Gi.exec(e))!==null;){const c=new ce(i[1]),h=c.TYPE;if(h){const u=o[h],d=r[h]||[];r[h]=d,Ce(s,c,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const g=c.LANGUAGE,f=c["ASSOC-LANGUAGE"],m=c.CHANNELS,E=c.CHARACTERISTICS,T=c["INSTREAM-ID"],y={attrs:c,bitrate:0,id:l++,groupId:c["GROUP-ID"]||"",name:c.NAME||g||"",type:h,default:c.bool("DEFAULT"),autoselect:c.bool("AUTOSELECT"),forced:c.bool("FORCED"),lang:g,url:c.URI?Xe.resolve(c.URI,t):""};if(f&&(y.assocLang=f),m&&(y.channels=m),E&&(y.characteristics=E),T&&(y.instreamId=T),u!=null&&u.length){const v=Xe.findGroup(u,y.groupId)||u[0];Vi(y,v,"audioCodec"),Vi(y,v,"textCodec")}d.push(y)}}return r}static parseLevelPlaylist(e,t,s,i,r,n){const o=new Wa(t),l=o.fragments;let c=null,h=0,u=0,d=0,g=0,f=null,m=new Ss(i,t),E,T,y,v=-1,A=!1,x=null;for($i.lastIndex=0,o.m3u8=e,o.hasVariableRefs=Oi(e);(E=$i.exec(e))!==null;){A&&(A=!1,m=new Ss(i,t),m.start=d,m.sn=h,m.cc=g,m.level=s,c&&(m.initSegment=c,m.rawProgramDateTime=c.rawProgramDateTime,c.rawProgramDateTime=null,x&&(m.setByteRange(x),x=null)));const k=E[1];if(k){m.duration=parseFloat(k);const I=(" "+E[2]).slice(1);m.title=I||null,m.tagList.push(I?["INF",k,I]:["INF",k])}else if(E[3]){if(N(m.duration)){m.start=d,y&&ji(m,y,o),m.sn=h,m.level=s,m.cc=g,l.push(m);const I=(" "+E[3]).slice(1);m.relurl=js(o,I),Wi(m,f),f=m,d+=m.duration,h++,u=0,A=!0}}else if(E[4]){const I=(" "+E[4]).slice(1);f?m.setByteRange(I,f):m.setByteRange(I)}else if(E[5])m.rawProgramDateTime=(" "+E[5]).slice(1),m.tagList.push(["PROGRAM-DATE-TIME",m.rawProgramDateTime]),v===-1&&(v=l.length);else{if(E=E[0].match(wo),!E){S.warn("No matches on slow regex match for level playlist!");continue}for(T=1;T<E.length&&!(typeof E[T]<"u");T++);const I=(" "+E[T]).slice(1),w=(" "+E[T+1]).slice(1),B=E[T+2]?(" "+E[T+2]).slice(1):"";switch(I){case"PLAYLIST-TYPE":o.type=w.toUpperCase();break;case"MEDIA-SEQUENCE":h=o.startSN=parseInt(w);break;case"SKIP":{const F=new ce(w);Ce(o,F,["RECENTLY-REMOVED-DATERANGES"]);const G=F.decimalInteger("SKIPPED-SEGMENTS");if(N(G)){o.skippedSegments=G;for(let U=G;U--;)l.unshift(null);h+=G}const V=F.enumeratedString("RECENTLY-REMOVED-DATERANGES");V&&(o.recentlyRemovedDateranges=V.split("	"));break}case"TARGETDURATION":o.targetduration=Math.max(parseInt(w),1);break;case"VERSION":o.version=parseInt(w);break;case"INDEPENDENT-SEGMENTS":case"EXTM3U":break;case"ENDLIST":o.live=!1;break;case"#":(w||B)&&m.tagList.push(B?[w,B]:[w]);break;case"DISCONTINUITY":g++,m.tagList.push(["DIS"]);break;case"GAP":m.gap=!0,m.tagList.push([I]);break;case"BITRATE":m.tagList.push([I,w]);break;case"DATERANGE":{const F=new ce(w);Ce(o,F,["ID","CLASS","START-DATE","END-DATE","SCTE35-CMD","SCTE35-OUT","SCTE35-IN"]),Ce(o,F,F.clientAttrs);const G=new Br(F,o.dateRanges[F.ID]);G.isValid||o.skippedSegments?o.dateRanges[G.id]=G:S.warn(`Ignoring invalid DATERANGE tag: "${w}"`),m.tagList.push(["EXT-X-DATERANGE",w]);break}case"DEFINE":{{const F=new ce(w);Ce(o,F,["NAME","VALUE","IMPORT","QUERYPARAM"]),"IMPORT"in F?Ao(o,F,n):Mi(o,F,t)}break}case"DISCONTINUITY-SEQUENCE":g=parseInt(w);break;case"KEY":{const F=Ki(w,t,o);if(F.isSupported()){if(F.method==="NONE"){y=void 0;break}y||(y={}),y[F.keyFormat]&&(y=me({},y)),y[F.keyFormat]=F}else S.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: "${w}"`);break}case"START":o.startTimeOffset=Hi(w);break;case"MAP":{const F=new ce(w);if(Ce(o,F,["BYTERANGE","URI"]),m.duration){const G=new Ss(i,t);Yi(G,F,s,y),c=G,m.initSegment=c,c.rawProgramDateTime&&!m.rawProgramDateTime&&(m.rawProgramDateTime=c.rawProgramDateTime)}else{const G=m.byteRangeEndOffset;if(G){const V=m.byteRangeStartOffset;x=`${G-V}@${V}`}else x=null;Yi(m,F,s,y),c=m,A=!0}break}case"SERVER-CONTROL":{const F=new ce(w);o.canBlockReload=F.bool("CAN-BLOCK-RELOAD"),o.canSkipUntil=F.optionalFloat("CAN-SKIP-UNTIL",0),o.canSkipDateRanges=o.canSkipUntil>0&&F.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=F.optionalFloat("PART-HOLD-BACK",0),o.holdBack=F.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const F=new ce(w);o.partTarget=F.decimalFloatingPoint("PART-TARGET");break}case"PART":{let F=o.partList;F||(F=o.partList=[]);const G=u>0?F[F.length-1]:void 0,V=u++,U=new ce(w);Ce(o,U,["BYTERANGE","URI"]);const Z=new Ha(U,m,t,V,G);F.push(Z),m.duration+=Z.duration;break}case"PRELOAD-HINT":{const F=new ce(w);Ce(o,F,["URI"]),o.preloadHint=F;break}case"RENDITION-REPORT":{const F=new ce(w);Ce(o,F,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(F);break}default:S.warn(`line parsed but not handled: ${E}`);break}}}f&&!f.relurl?(l.pop(),d-=f.duration,o.partList&&(o.fragmentHint=f)):o.partList&&(Wi(m,f),m.cc=g,o.fragmentHint=m,y&&ji(m,y,o));const D=l.length,R=l[0],C=l[D-1];if(d+=o.skippedSegments*o.targetduration,d>0&&D&&C){o.averagetargetduration=d/D;const k=C.sn;o.endSN=k!=="initSegment"?k:0,o.live||(C.endList=!0),R&&(o.startCC=R.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(d+=o.fragmentHint.duration),o.totalduration=d,o.endCC=g,v>0&&Po(l,v),o}}function Ki(a,e,t){var s,i;const r=new ce(a);Ce(t,r,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const n=(s=r.METHOD)!=null?s:"",o=r.URI,l=r.hexadecimalInteger("IV"),c=r.KEYFORMATVERSIONS,h=(i=r.KEYFORMAT)!=null?i:"identity";o&&r.IV&&!l&&S.error(`Invalid IV: ${r.IV}`);const u=o?Xe.resolve(o,e):"",d=(c||"1").split("/").map(Number).filter(Number.isFinite);return new Pt(n,u,h,d,l)}function Hi(a){const t=new ce(a).decimalFloatingPoint("TIME-OFFSET");return N(t)?t:null}function ko(a,e){let t=(a||"").split(/[ ,]+/).filter(s=>s);["video","audio","text"].forEach(s=>{const i=t.filter(r=>bo(r,s));i.length&&(e[`${s}Codec`]=i.join(","),t=t.filter(r=>i.indexOf(r)===-1))}),e.unknownCodecs=t}function Vi(a,e,t){const s=e[t];s&&(a[t]=s)}function Po(a,e){let t=a[e];for(let s=e;s--;){const i=a[s];if(!i)return;i.programDateTime=t.programDateTime-i.duration*1e3,t=i}}function Wi(a,e){a.rawProgramDateTime?a.programDateTime=Date.parse(a.rawProgramDateTime):e!=null&&e.programDateTime&&(a.programDateTime=e.endProgramDateTime),N(a.programDateTime)||(a.programDateTime=null,a.rawProgramDateTime=null)}function Yi(a,e,t,s){a.relurl=e.URI,e.BYTERANGE&&a.setByteRange(e.BYTERANGE),a.level=t,a.sn="initSegment",s&&(a.levelkeys=s),a.initSegment=null}function ji(a,e,t){a.levelkeys=e;const{encryptedFragments:s}=t;(!s.length||s[s.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&s.push(a)}var te={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},H={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function zi(a){const{type:e}=a;switch(e){case te.AUDIO_TRACK:return H.AUDIO;case te.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function Cs(a,e){let t=a.url;return(t===void 0||t.indexOf("data:")===0)&&(t=e.url),t}class Fo{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(p.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const t=this.hls.config,s=t.pLoader,i=t.loader,r=s||i,n=new r(t);return this.loaders[e.type]=n,n}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:s}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:te.MANIFEST,url:s,deliveryDirectives:null})}onLevelLoading(e,t){const{id:s,level:i,pathwayId:r,url:n,deliveryDirectives:o}=t;this.load({id:s,level:i,pathwayId:r,responseType:"text",type:te.LEVEL,url:n,deliveryDirectives:o})}onAudioTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.AUDIO_TRACK,url:r,deliveryDirectives:n})}onSubtitleTrackLoading(e,t){const{id:s,groupId:i,url:r,deliveryDirectives:n}=t;this.load({id:s,groupId:i,level:null,responseType:"text",type:te.SUBTITLE_TRACK,url:r,deliveryDirectives:n})}load(e){var t;const s=this.hls.config;let i=this.getInternalLoader(e);if(i){const c=i.context;if(c&&c.url===e.url&&c.level===e.level){S.trace("[playlist-loader]: playlist request ongoing");return}S.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let r;if(e.type===te.MANIFEST?r=s.manifestLoadPolicy.default:r=me({},s.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),N((t=e.deliveryDirectives)==null?void 0:t.part)){let c;if(e.type===te.LEVEL&&e.level!==null?c=this.hls.levels[e.level].details:e.type===te.AUDIO_TRACK&&e.id!==null?c=this.hls.audioTracks[e.id].details:e.type===te.SUBTITLE_TRACK&&e.id!==null&&(c=this.hls.subtitleTracks[e.id].details),c){const h=c.partTarget,u=c.targetduration;if(h&&u){const d=Math.max(h*3,u*.8)*1e3;r=me({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}}const n=r.errorRetry||r.timeoutRetry||{},o={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:n.maxNumRetry||0,retryDelay:n.retryDelayMs||0,maxRetryDelay:n.maxRetryDelayMs||0},l={onSuccess:(c,h,u,d)=>{const g=this.getInternalLoader(u);this.resetInternalLoader(u.type);const f=c.data;if(f.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(c,u,new Error("no EXTM3U delimiter"),d||null,h);return}h.parsing.start=performance.now(),Xe.isMediaPlaylist(f)?this.handleTrackOrLevelPlaylist(c,h,u,d||null,g):this.handleMasterPlaylist(c,h,u,d)},onError:(c,h,u,d)=>{this.handleNetworkError(h,u,!1,c,d)},onTimeout:(c,h,u)=>{this.handleNetworkError(h,u,!0,void 0,c)}};i.load(e,o,l)}handleMasterPlaylist(e,t,s,i){const r=this.hls,n=e.data,o=Cs(e,s),l=Xe.parseMasterPlaylist(n,o);if(l.playlistParsingError){this.handleManifestParsingError(e,s,l.playlistParsingError,i,t);return}const{contentSteering:c,levels:h,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f}=l;this.variableList=f;const{AUDIO:m=[],SUBTITLES:E,"CLOSED-CAPTIONS":T}=Xe.parseMasterPlaylistMedia(n,o,l);m.length&&!m.some(v=>!v.url)&&h[0].audioCodec&&!h[0].attrs.AUDIO&&(S.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new ce({}),bitrate:0,url:""})),r.trigger(p.MANIFEST_LOADED,{levels:h,audioTracks:m,subtitles:E,captions:T,contentSteering:c,url:o,stats:t,networkDetails:i,sessionData:u,sessionKeys:d,startTimeOffset:g,variableList:f})}handleTrackOrLevelPlaylist(e,t,s,i,r){const n=this.hls,{id:o,level:l,type:c}=s,h=Cs(e,s),u=0,d=N(l)?l:N(o)?o:0,g=zi(s),f=Xe.parseLevelPlaylist(e.data,h,d,g,u,this.variableList);if(c===te.MANIFEST){const m={attrs:new ce({}),bitrate:0,details:f,name:"",url:h};n.trigger(p.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:h,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),s.levelDetails=f,this.handlePlaylistLoaded(f,e,t,s,i,r)}handleManifestParsingError(e,t,s,i,r){this.hls.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.MANIFEST_PARSING_ERROR,fatal:t.type===te.MANIFEST,url:e.url,err:s,error:s,reason:s.message,response:e,context:t,networkDetails:i,stats:r})}handleNetworkError(e,t,s=!1,i,r){let n=`A network ${s?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===te.LEVEL?n+=`: ${e.level} id: ${e.id}`:(e.type===te.AUDIO_TRACK||e.type===te.SUBTITLE_TRACK)&&(n+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(n);S.warn(`[playlist-loader]: ${n}`);let l=b.UNKNOWN,c=!1;const h=this.getInternalLoader(e);switch(e.type){case te.MANIFEST:l=s?b.MANIFEST_LOAD_TIMEOUT:b.MANIFEST_LOAD_ERROR,c=!0;break;case te.LEVEL:l=s?b.LEVEL_LOAD_TIMEOUT:b.LEVEL_LOAD_ERROR,c=!1;break;case te.AUDIO_TRACK:l=s?b.AUDIO_TRACK_LOAD_TIMEOUT:b.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case te.SUBTITLE_TRACK:l=s?b.SUBTITLE_TRACK_LOAD_TIMEOUT:b.SUBTITLE_LOAD_ERROR,c=!1;break}h&&this.resetInternalLoader(e.type);const u={type:W.NETWORK_ERROR,details:l,fatal:c,url:e.url,loader:h,context:e,error:o,networkDetails:t,stats:r};if(i){const d=t?.url||e.url;u.response=Le({url:d,data:void 0},i)}this.hls.trigger(p.ERROR,u)}handlePlaylistLoaded(e,t,s,i,r,n){const o=this.hls,{type:l,level:c,id:h,groupId:u,deliveryDirectives:d}=i,g=Cs(t,i),f=zi(i),m=typeof i.level=="number"&&f===H.MAIN?c:void 0;if(!e.fragments.length){const T=new Error("No Segments found in Playlist");o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:T,reason:T.message,response:t,context:i,level:m,parent:f,networkDetails:r,stats:s});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const E=e.playlistParsingError;if(E){o.trigger(p.ERROR,{type:W.NETWORK_ERROR,details:b.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:E,reason:E.message,response:t,context:i,level:m,parent:f,networkDetails:r,stats:s});return}switch(e.live&&n&&(n.getCacheAge&&(e.ageHeader=n.getCacheAge()||0),(!n.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case te.MANIFEST:case te.LEVEL:o.trigger(p.LEVEL_LOADED,{details:e,level:m||0,id:h||0,stats:s,networkDetails:r,deliveryDirectives:d});break;case te.AUDIO_TRACK:o.trigger(p.AUDIO_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break;case te.SUBTITLE_TRACK:o.trigger(p.SUBTITLE_TRACK_LOADED,{details:e,id:h||0,groupId:u||"",stats:s,networkDetails:r,deliveryDirectives:d});break}}}function tn(a,e){let t;try{t=new Event("addtrack")}catch{t=document.createEvent("Event"),t.initEvent("addtrack",!1,!1)}t.track=a,e.dispatchEvent(t)}function sn(a,e){const t=a.mode;if(t==="disabled"&&(a.mode="hidden"),a.cues&&!a.cues.getCueById(e.id))try{if(a.addCue(e),!a.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(s){S.debug(`[texttrack-utils]: ${s}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,a.addCue(i)}catch(i){S.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}t==="disabled"&&(a.mode=t)}function vt(a){const e=a.mode;if(e==="disabled"&&(a.mode="hidden"),a.cues)for(let t=a.cues.length;t--;)a.removeCue(a.cues[t]);e==="disabled"&&(a.mode=e)}function zs(a,e,t,s){const i=a.mode;if(i==="disabled"&&(a.mode="hidden"),a.cues&&a.cues.length>0){const r=Mo(a.cues,e,t);for(let n=0;n<r.length;n++)(!s||s(r[n]))&&a.removeCue(r[n])}i==="disabled"&&(a.mode=i)}function Oo(a,e){if(e<a[0].startTime)return 0;const t=a.length-1;if(e>a[t].endTime)return-1;let s=0,i=t;for(;s<=i;){const r=Math.floor((i+s)/2);if(e<a[r].startTime)i=r-1;else if(e>a[r].startTime&&s<t)s=r+1;else return r}return a[s].startTime-e<e-a[i].startTime?s:i}function Mo(a,e,t){const s=[],i=Oo(a,e);if(i>-1)for(let r=i,n=a.length;r<n;r++){const o=a[r];if(o.startTime>=e&&o.endTime<=t)s.push(o);else if(o.startTime>t)return s}return s}function Xt(a){const e=[];for(let t=0;t<a.length;t++){const s=a[t];(s.kind==="subtitles"||s.kind==="captions")&&s.label&&e.push(a[t])}return e}var Ye={audioId3:"org.id3",dateRange:"com.apple.quicktime.HLS",emsg:"https://aomedia.org/emsg/ID3"};const No=.25;function qs(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function qi(a,e,t,s,i){let r=new a(e,t,"");try{r.value=s,i&&(r.type=i)}catch{r=new a(e,t,JSON.stringify(i?Le({type:i},s):s))}return r}const Gt=(()=>{const a=qs();try{a&&new a(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function _s(a,e){return a.getTime()/1e3-e}function Uo(a){return Uint8Array.from(a.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class Bo{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,t){this.media=t.media}onMediaDetaching(){this.id3Track&&(vt(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const s=e[t];if(s.kind==="metadata"&&s.label==="id3")return tn(s,this.media),s}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media)return;const{hls:{config:{enableEmsgMetadataCues:s,enableID3MetadataCues:i}}}=this;if(!s&&!i)return;const{samples:r}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const n=qs();if(n)for(let o=0;o<r.length;o++){const l=r[o].type;if(l===Ye.emsg&&!s||!i)continue;const c=Wr(r[o].data);if(c){const h=r[o].pts;let u=h+r[o].duration;u>Gt&&(u=Gt),u-h<=0&&(u=h+No);for(let g=0;g<c.length;g++){const f=c[g];if(!Vr(f)){this.updateId3CueEnds(h,l);const m=qi(n,h,u,f,l);m&&this.id3Track.addCue(m)}}}}}updateId3CueEnds(e,t){var s;const i=(s=this.id3Track)==null?void 0:s.cues;if(i)for(let r=i.length;r--;){const n=i[r];n.type===t&&n.startTime<e&&n.endTime===Gt&&(n.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:s,type:i}){const{id3Track:r,hls:n}=this;if(!n)return;const{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:l}}=n;if(r&&(o||l)){let c;i==="audio"?c=h=>h.type===Ye.audioId3&&l:i==="video"?c=h=>h.type===Ye.emsg&&o:c=h=>h.type===Ye.audioId3&&l||h.type===Ye.emsg&&o,zs(r,t,s,c)}}onLevelUpdated(e,{details:t}){if(!this.media||!t.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:s,id3Track:i}=this,{dateRanges:r}=t,n=Object.keys(r);if(i){const h=Object.keys(s).filter(u=>!n.includes(u));for(let u=h.length;u--;){const d=h[u];Object.keys(s[d].cues).forEach(g=>{i.removeCue(s[d].cues[g])}),delete s[d]}}const o=t.fragments[t.fragments.length-1];if(n.length===0||!N(o?.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,c=qs();for(let h=0;h<n.length;h++){const u=n[h],d=r[u],g=_s(d.startDate,l),f=s[u],m=f?.cues||{};let E=f?.durationKnown||!1,T=Gt;const y=d.endDate;if(y)T=_s(y,l),E=!0;else if(d.endOnNext&&!E){const A=n.reduce((x,D)=>{if(D!==d.id){const R=r[D];if(R.class===d.class&&R.startDate>d.startDate&&(!x||d.startDate<x.startDate))return R}return x},null);A&&(T=_s(A.startDate,l),E=!0)}const v=Object.keys(d.attr);for(let A=0;A<v.length;A++){const x=v[A];if(!$a(x))continue;const D=m[x];if(D)E&&!f.durationKnown&&(D.endTime=T);else if(c){let R=d.attr[x];Ka(x)&&(R=Uo(R));const C=qi(c,g,T,{key:x,data:R},Ye.dateRange);C&&(C.id=u,this.id3Track.addCue(C),m[x]=C)}}s[u]={cues:m,dateRange:d,durationKnown:E}}}}class Go{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.levelDetails=null,this.currentTime=0,this.stallCount=0,this._latency=null,this.timeupdateHandler=()=>this.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:t}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:t,partHoldBack:s,targetduration:i}=e,{liveSyncDuration:r,liveSyncDurationCount:n,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let c=o&&s||t;(l.liveSyncDuration||l.liveSyncDurationCount||c===0)&&(c=r!==void 0?r:n*i);const h=i;return c+Math.min(this.stallCount*1,h)}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency,s=this.levelDetails;if(e===null||t===null||s===null)return null;const i=s.edge,r=e-t-this.edgeStalled,n=i-s.totalduration,o=i-(this.config.lowLatencyMode&&s.partTarget||s.targetduration);return Math.min(Math.max(n,r),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e,levelDetails:t}=this;if(!e||!t)return 0;const s=e.buffered.length;return(s?e.buffered.end(s-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(p.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(p.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){this.levelDetails=t,t.advanced&&this.timeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,t){var s;t.details===b.BUFFER_STALLED_ERROR&&(this.stallCount++,(s=this.levelDetails)!=null&&s.live&&S.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:t}=this;if(!e||!t)return;this.currentTime=e.currentTime;const s=this.computeLatency();if(s===null)return;this._latency=s;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:r}=this.config;if(!i||r===1||!t.live)return;const n=this.targetLatency;if(n===null)return;const o=s-n,l=Math.min(this.maxLatency,n+t.targetduration);if(o<l&&o>.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,r)),u=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(h,Math.max(1,u))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Xs=["NONE","TYPE-0","TYPE-1",null];function $o(a){return Xs.indexOf(a)>-1}const ls=["SDR","PQ","HLG"];function Ko(a){return!!a&&ls.indexOf(a)>-1}var Qt={No:"",Yes:"YES",v2:"v2"};function Xi(a){const{canSkipUntil:e,canSkipDateRanges:t,age:s}=a,i=s<e/2;return e&&i?t?Qt.v2:Qt.Yes:Qt.No}class Qi{constructor(e,t,s){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=s}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}}class Rt{constructor(e){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(t=>!!t).map(t=>t.substring(0,4)).join(","),this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return Ji(this._audioGroups,e)}hasSubtitleGroup(e){return Ji(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let s=this._audioGroups;s||(s=this._audioGroups=[]),s.indexOf(t)===-1&&s.push(t)}else if(e==="text"){let s=this._subtitleGroups;s||(s=this._subtitleGroups=[]),s.indexOf(t)===-1&&s.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}}function Ji(a,e){return!e||!a?!1:a.indexOf(e)!==-1}function ws(a,e){const t=e.startPTS;if(N(t)){let s=0,i;e.sn>a.sn?(s=t-a.start,i=a):(s=a.start-t,i=e),i.duration!==s&&(i.duration=s)}else e.sn>a.sn?a.cc===e.cc&&a.minEndPTS?e.start=a.start+(a.minEndPTS-a.start):e.start=a.start+a.duration:e.start=Math.max(a.start-e.duration,0)}function rn(a,e,t,s,i,r){s-t<=0&&(S.warn("Fragment should have a positive duration",e),s=t+e.duration,r=i+e.duration);let o=t,l=s;const c=e.startPTS,h=e.endPTS;if(N(c)){const E=Math.abs(c-t);N(e.deltaPTS)?e.deltaPTS=Math.max(E,e.deltaPTS):e.deltaPTS=E,o=Math.max(t,c),t=Math.min(t,c),i=Math.min(i,e.startDTS),l=Math.min(s,h),s=Math.max(s,h),r=Math.max(r,e.endDTS)}const u=t-e.start;e.start!==0&&(e.start=t),e.duration=s-e.start,e.startPTS=t,e.maxStartPTS=o,e.startDTS=i,e.endPTS=s,e.minEndPTS=l,e.endDTS=r;const d=e.sn;if(!a||d<a.startSN||d>a.endSN)return 0;let g;const f=d-a.startSN,m=a.fragments;for(m[f]=e,g=f;g>0;g--)ws(m[g],m[g-1]);for(g=f;g<m.length-1;g++)ws(m[g],m[g+1]);return a.fragmentHint&&ws(m[m.length-1],a.fragmentHint),a.PTSKnown=a.alignedSliding=!0,u}function Ho(a,e){let t=null;const s=a.fragments;for(let l=s.length-1;l>=0;l--){const c=s[l].initSegment;if(c){t=c;break}}a.fragmentHint&&delete a.fragmentHint.endPTS;let i=0,r;if(Yo(a,e,(l,c)=>{l.relurl&&(i=l.cc-c.cc),N(l.startPTS)&&N(l.endPTS)&&(c.start=c.startPTS=l.startPTS,c.startDTS=l.startDTS,c.maxStartPTS=l.maxStartPTS,c.endPTS=l.endPTS,c.endDTS=l.endDTS,c.minEndPTS=l.minEndPTS,c.duration=l.endPTS-l.startPTS,c.duration&&(r=c),e.PTSKnown=e.alignedSliding=!0),c.elementaryStreams=l.elementaryStreams,c.loader=l.loader,c.stats=l.stats,l.initSegment&&(c.initSegment=l.initSegment,t=l.initSegment)}),t&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(c=>{var h;c&&(!c.initSegment||c.initSegment.relurl===((h=t)==null?void 0:h.relurl))&&(c.initSegment=t)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){S.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=Vo(a.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const n=e.fragments;if(i){S.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l<n.length;l++)n[l].cc+=i}e.skippedSegments&&(e.startCC=e.fragments[0].cc),Wo(a.partList,e.partList,(l,c)=>{c.elementaryStreams=l.elementaryStreams,c.stats=l.stats}),r?rn(e,r,r.startPTS,r.endPTS,r.startDTS,r.endDTS):nn(a,e),n.length&&(e.totalduration=e.edge-n[0].start),e.driftStartTime=a.driftStartTime,e.driftStart=a.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=a.driftEndTime,e.driftEnd=a.driftEnd,e.advancedDateTime=a.advancedDateTime}function Vo(a,e,t){const s=me({},a);return t&&t.forEach(i=>{delete s[i]}),Object.keys(e).forEach(i=>{const r=new Br(e[i].attr,s[i]);r.isValid?s[i]=r:S.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),s}function Wo(a,e,t){if(a&&e){let s=0;for(let i=0,r=a.length;i<=r;i++){const n=a[i],o=e[i+s];n&&o&&n.index===o.index&&n.fragment.sn===o.fragment.sn?t(n,o):s--}}}function Yo(a,e,t){const s=e.skippedSegments,i=Math.max(a.startSN,e.startSN)-e.startSN,r=(a.fragmentHint?1:0)+(s?e.endSN:Math.min(a.endSN,e.endSN))-e.startSN,n=e.startSN-a.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=a.fragmentHint?a.fragments.concat(a.fragmentHint):a.fragments;for(let c=i;c<=r;c++){const h=l[n+c];let u=o[c];s&&!u&&c<s&&(u=e.fragments[c]=h),h&&u&&t(h,u)}}function nn(a,e){const t=e.startSN+e.skippedSegments-a.startSN,s=a.fragments;t<0||t>=s.length||Qs(e,s[t].start)}function Qs(a,e){if(e){const t=a.fragments;for(let s=a.skippedSegments;s<t.length;s++)t[s].start+=e;a.fragmentHint&&(a.fragmentHint.start+=e)}}function jo(a,e=1/0){let t=1e3*a.targetduration;if(a.updated){const s=a.fragments;if(s.length&&t*4>e){const r=s[s.length-1].duration*1e3;r<t&&(t=r)}}else t/=2;return Math.round(t)}function zo(a,e,t){if(!(a!=null&&a.details))return null;const s=a.details;let i=s.fragments[e-s.startSN];return i||(i=s.fragmentHint,i&&i.sn===e)?i:e<s.startSN&&t&&t.sn===e?t:null}function Zi(a,e,t){var s;return a!=null&&a.details?an((s=a.details)==null?void 0:s.partList,e,t):null}function an(a,e,t){if(a)for(let s=a.length;s--;){const i=a[s];if(i.index===t&&i.fragment.sn===e)return i}return null}function on(a){a.forEach((e,t)=>{const{details:s}=e;s!=null&&s.fragments&&s.fragments.forEach(i=>{i.level=t})})}function cs(a){switch(a.details){case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_TIMEOUT:case b.LEVEL_LOAD_TIMEOUT:case b.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function er(a,e){const t=cs(e);return a.default[`${t?"timeout":"error"}Retry`]}function fi(a,e){const t=a.backoff==="linear"?1:Math.pow(2,e);return Math.min(t*a.retryDelayMs,a.maxRetryDelayMs)}function tr(a){return Le(Le({},a),{errorRetry:null,timeoutRetry:null})}function hs(a,e,t,s){if(!a)return!1;const i=s?.code,r=e<a.maxNumRetry&&(qo(i)||!!t);return a.shouldRetry?a.shouldRetry(a,e,t,s,r):r}function qo(a){return a===0&&navigator.onLine===!1||!!a&&(a<400||a>499)}const ln={search:function(a,e){let t=0,s=a.length-1,i=null,r=null;for(;t<=s;){i=(t+s)/2|0,r=a[i];const n=e(r);if(n>0)t=i+1;else if(n<0)s=i-1;else return r}return null}};function Xo(a,e,t){if(e===null||!Array.isArray(a)||!a.length||!N(e))return null;const s=a[0].programDateTime;if(e<(s||0))return null;const i=a[a.length-1].endProgramDateTime;if(e>=(i||0))return null;t=t||0;for(let r=0;r<a.length;++r){const n=a[r];if(Jo(e,t,n))return n}return null}function us(a,e,t=0,s=0,i=.005){let r=null;if(a){r=e[a.sn-e[0].sn+1]||null;const o=a.endDTS-t;o>0&&o<15e-7&&(t+=15e-7)}else t===0&&e[0].start===0&&(r=e[0]);if(r&&((!a||a.level===r.level)&&Js(t,s,r)===0||Qo(r,a,Math.min(i,s))))return r;const n=ln.search(e,Js.bind(null,t,s));return n&&(n!==a||!r)?n:r}function Qo(a,e,t){if(e&&e.start===0&&e.level<a.level&&(e.endPTS||0)>0){const s=e.tagList.reduce((i,r)=>(r[0]==="INF"&&(i+=parseFloat(r[1])),i),t);return a.start<=s}return!1}function Js(a=0,e=0,t){if(t.start<=a&&t.start+t.duration>a)return 0;const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0));return t.start+t.duration-s<=a?1:t.start-s>a&&t.start?-1:0}function Jo(a,e,t){const s=Math.min(e,t.duration+(t.deltaPTS?t.deltaPTS:0))*1e3;return(t.endProgramDateTime||0)-s>a}function Zo(a,e){return ln.search(a,t=>t.cc<e?1:t.cc>e?-1:0)}var Ae={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Ve={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2};class el{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=S.log.bind(S,"[info]:"),this.warn=S.warn.bind(S,"[warning]:"),this.error=S.error.bind(S,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(p.ERROR,this.onError,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(p.ERROR,this.onError,this),e.off(p.ERROR,this.onErrorOut,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===H.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,t){var s,i;if(t.fatal)return;const r=this.hls,n=t.context;switch(t.details){case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case b.FRAG_PARSING_ERROR:if((s=t.frag)!=null&&s.gap){t.errorAction={action:Ae.DoNothing,flags:Ve.None};return}case b.FRAG_GAP:case b.FRAG_DECRYPT_ERROR:{t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Ae.SendAlternateToPenaltyBox;return}case b.LEVEL_EMPTY_ERROR:case b.LEVEL_PARSING_ERROR:{var o,l;const c=t.parent===H.MAIN?t.level:r.loadLevel;t.details===b.LEVEL_EMPTY_ERROR&&((o=t.context)!=null&&(l=o.levelDetails)!=null&&l.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,c):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,c))}return;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:typeof n?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level));return;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.SUBTITLE_LOAD_ERROR:case b.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){const c=r.levels[r.loadLevel];if(c&&(n.type===te.AUDIO_TRACK&&c.hasAudioGroup(n.groupId)||n.type===te.SUBTITLE_TRACK&&c.hasSubtitleGroup(n.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=Ae.SendAlternateToPenaltyBox,t.errorAction.flags=Ve.MoveAllAlternatesMatchingHost;return}}return;case b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const c=r.levels[r.loadLevel],h=c?.attrs["HDCP-LEVEL"];h?t.errorAction={action:Ae.SendAlternateToPenaltyBox,flags:Ve.MoveAllAlternatesMatchingHDCP,hdcpLevel:h}:this.keySystemError(t)}return;case b.BUFFER_ADD_CODEC_ERROR:case b.REMUX_ALLOC_ERROR:case b.BUFFER_APPEND_ERROR:t.errorAction=this.getLevelSwitchAction(t,(i=t.level)!=null?i:r.loadLevel);return;case b.INTERNAL_EXCEPTION:case b.BUFFER_APPENDING_ERROR:case b.BUFFER_FULL_ERROR:case b.LEVEL_SWITCH_ERROR:case b.BUFFER_STALLED_ERROR:case b.BUFFER_SEEK_OVER_HOLE:case b.BUFFER_NUDGE_ON_STALL:t.errorAction={action:Ae.DoNothing,flags:Ve.None};return}t.type===W.KEY_SYSTEM_ERROR&&this.keySystemError(t)}keySystemError(e){const t=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,t)}getPlaylistRetryOrSwitchAction(e,t){const s=this.hls,i=er(s.config.playlistLoadPolicy,e),r=this.playlistError++;if(hs(i,r,cs(e),e.response))return{action:Ae.RetryRequest,flags:Ve.None,retryConfig:i,retryCount:r};const o=this.getLevelSwitchAction(e,t);return i&&(o.retryConfig=i,o.retryCount=r),o}getFragRetryOrSwitchAction(e){const t=this.hls,s=this.getVariantLevelIndex(e.frag),i=t.levels[s],{fragLoadPolicy:r,keyLoadPolicy:n}=t.config,o=er(e.details.startsWith("key")?n:r,e),l=t.levels.reduce((h,u)=>h+u.fragmentError,0);if(i&&(e.details!==b.FRAG_GAP&&i.fragmentError++,hs(o,l,cs(e),e.response)))return{action:Ae.RetryRequest,flags:Ve.None,retryConfig:o,retryCount:l};const c=this.getLevelSwitchAction(e,s);return o&&(c.retryConfig=o,c.retryCount=l),c}getLevelSwitchAction(e,t){const s=this.hls;t==null&&(t=s.loadLevel);const i=this.hls.levels[t];if(i){var r,n;const c=e.details;i.loadError++,c===b.BUFFER_APPEND_ERROR&&i.fragmentError++;let h=-1;const{levels:u,loadLevel:d,minAutoLevel:g,maxAutoLevel:f}=s;s.autoLevelEnabled||(s.loadLevel=-1);const m=(r=e.frag)==null?void 0:r.type,T=(m===H.AUDIO&&c===b.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(c===b.BUFFER_ADD_CODEC_ERROR||c===b.BUFFER_APPEND_ERROR))&&u.some(({audioCodec:D})=>i.audioCodec!==D),v=e.sourceBufferName==="video"&&(c===b.BUFFER_ADD_CODEC_ERROR||c===b.BUFFER_APPEND_ERROR)&&u.some(({codecSet:D,audioCodec:R})=>i.codecSet!==D&&i.audioCodec===R),{type:A,groupId:x}=(n=e.context)!=null?n:{};for(let D=u.length;D--;){const R=(D+d)%u.length;if(R!==d&&R>=g&&R<=f&&u[R].loadError===0){var o,l;const C=u[R];if(c===b.FRAG_GAP&&m===H.MAIN&&e.frag){const k=u[R].details;if(k){const I=us(e.frag,k.fragments,e.frag.start);if(I!=null&&I.gap)continue}}else{if(A===te.AUDIO_TRACK&&C.hasAudioGroup(x)||A===te.SUBTITLE_TRACK&&C.hasSubtitleGroup(x))continue;if(m===H.AUDIO&&(o=i.audioGroups)!=null&&o.some(k=>C.hasAudioGroup(k))||m===H.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(k=>C.hasSubtitleGroup(k))||T&&i.audioCodec===C.audioCodec||!T&&i.audioCodec!==C.audioCodec||v&&i.codecSet===C.codecSet)continue}h=R;break}}if(h>-1&&s.loadLevel!==h)return e.levelRetry=!0,this.playlistError=0,{action:Ae.SendAlternateToPenaltyBox,flags:Ve.None,nextAutoLevel:h}}return{action:Ae.SendAlternateToPenaltyBox,flags:Ve.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var s;switch((s=t.errorAction)==null?void 0:s.action){case Ae.DoNothing:break;case Ae.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==b.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}
1" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,s=e.errorAction;if(!s)return;const{flags:i,hdcpLevel:r,nextAutoLevel:n}=s;switch(i){case Ve.None:this.switchLevel(e,n);break;case Ve.MoveAllAlternatesMatchingHDCP:r&&(t.maxHdcpLevel=Xs[Xs.indexOf(r)-1],s.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}s.resolved||this.switchLevel(e,n)}switchLevel(e,t){t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class gi{constructor(e,t){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=S.log.bind(S,`${t}:`),this.warn=S.warn.bind(S,`${t}:`),this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,s){const i=t?.renditionReports;if(i){let r=-1;for(let n=0;n<i.length;n++){const o=i[n];let l;try{l=new self.URL(o.URI,t.url).href}catch(c){S.warn(`Could not construct new URL for Rendition Report: ${c}`),l=o.URI||""}if(l===e){r=n;break}else l===e.substring(0,l.length)&&(r=n)}if(r!==-1){const n=i[r],o=parseInt(n["LAST-MSN"])||t?.lastPartSn;let l=parseInt(n["LAST-PART"])||t?.lastPartIndex;if(this.hls.config.lowLatencyMode){const h=Math.min(t.age-t.partTarget,t.targetduration);l>=0&&h>t.partTarget&&(l+=1)}const c=s&&Xi(s);return new Qi(o,l>=0?l:void 0,c)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,t,s){const{details:i,stats:r}=t,n=self.performance.now(),o=r.loading.first?Math.max(0,n-r.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||s!=null&&s.live){if(i.reloaded(s),s&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),s&&i.fragments.length>0&&Ho(s,i),!this.canLoad||!i.live)return;let l,c,h;if(i.canBlockReload&&i.endSN&&i.advanced){const E=this.hls.config.lowLatencyMode,T=i.lastPartSn,y=i.endSN,v=i.lastPartIndex,A=v!==-1,x=T===y,D=E?0:v;A?(c=x?y+1:T,h=x?D:v+1):c=y+1;const R=i.age,C=R+i.ageHeader;let k=Math.min(C-i.partTarget,i.targetduration*1.5);if(k>0){if(s&&k>s.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${s.tuneInGoal} to: ${k} with playlist age: ${i.age}`),k=0;else{const I=Math.floor(k/i.targetduration);if(c+=I,h!==void 0){const w=Math.round(k%i.targetduration/i.partTarget);h+=w}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${R.toFixed(2)}s goal: ${k} skip sn ${I} to part ${h}`)}i.tuneInGoal=k}if(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h),E||!x){this.loadPlaylist(l);return}}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,t.deliveryDirectives,c,h));const u=this.hls.mainForwardBufferInfo,d=u?u.end-u.len:0,g=(i.edge-d)*1e3,f=jo(i,g);i.updated&&n>this.requestScheduled+f&&(this.requestScheduled=r.loading.start),c!==void 0&&i.canBlockReload?this.requestScheduled=r.loading.first+f-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+f<n?this.requestScheduled=n:this.requestScheduled-n<=0&&(this.requestScheduled+=f);let m=this.requestScheduled-n;m=Math.max(0,m),this.log(`reload live playlist ${e} in ${Math.round(m)} ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(l),m)}else this.clearTimer()}getDeliveryDirectives(e,t,s,i){let r=Xi(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(s=t.msn,i=t.part,r=Qt.No),new Qi(s,i,r)}checkRetry(e){const t=e.details,s=cs(e),i=e.errorAction,{action:r,retryCount:n=0,retryConfig:o}=i||{}
vendor: 16,084 bytes, lines 1-8
1,l=!!i&&!!o&&(r===Ae.RetryRequest||!i.resolved&&r===Ae.SendAlternateToPenaltyBox);if(l){var c;if(this.requestScheduled=-1,n>=o.maxNumRetry)return!1;if(s&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const h=fi(o,n);this.timer=self.setTimeout(()=>this.loadPlaylist(),h),this.warn(`Retrying playlist loading ${n+1}/${o.maxNumRetry} after "${t}" in ${h}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}class mt{constructor(e,t=0,s=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=s}sample(e,t){const s=Math.pow(this.alpha_,e);this.estimate_=t*(1-s)+s*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}}class tl{constructor(e,t,s,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=s,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new mt(e),this.fast_=new mt(t),this.defaultTTFB_=i,this.ttfb_=new mt(e)}update(e,t){const{slow_:s,fast_:i,ttfb_:r}=this;s.halfLife!==e&&(this.slow_=new mt(e,s.getEstimate(),s.getTotalWeight())),i.halfLife!==t&&(this.fast_=new mt(t,i.getEstimate(),i.getTotalWeight())),r.halfLife!==e&&(this.ttfb_=new mt(e,r.getEstimate(),r.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const s=8*t,i=e/1e3,r=s/i;this.fast_.sample(i,r),this.slow_.sample(i,r)}sampleTTFB(e){const t=e/1e3,s=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(s,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const cn={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},sr={};function sl(a,e,t,s,i,r){const n=a.audioCodec?a.audioGroups:null,o=r?.audioCodec,l=r?.channels,c=l?parseInt(l):o?1/0:2;let h=null;if(n!=null&&n.length)try{n.length===1&&n[0]?h=e.groups[n[0]].channels:h=n.reduce((u,d)=>{if(d){const g=e.groups[d];if(!g)throw new Error(`Audio track group ${d} not found`);Object.keys(g.channels).forEach(f=>{u[f]=(u[f]||0)+g.channels[f]})}return u},{2:0})}catch{return!0}return a.videoCodec!==void 0&&(a.width>1920&&a.height>1088||a.height>1920&&a.width>1088||a.frameRate>Math.max(s,30)||a.videoRange!=="SDR"&&a.videoRange!==t||a.bitrate>Math.max(i,8e6))||!!h&&N(c)&&Object.keys(h).some(u=>parseInt(u)>c)}function il(a,e,t){const s=a.videoCodec,i=a.audioCodec;if(!s||!i||!t)return Promise.resolve(cn);const r={width:a.width,height:a.height,bitrate:Math.ceil(Math.max(a.bitrate*.9,a.averageBitrate)),framerate:a.frameRate||30},n=a.videoRange;n!=="SDR"&&(r.transferFunction=n.toLowerCase());const o=s.split(",").map(l=>({type:"media-source",video:Le(Le({},r),{},{contentType:Ft(l,"video")})}));return i&&a.audioGroups&&a.audioGroups.forEach(l=>{var c;l&&((c=e.groups[l])==null||c.tracks.forEach(h=>{if(h.groupId===l){const u=h.channels||"",d=parseFloat(u);N(d)&&d>2&&o.push.apply(o,i.split(",").map(g=>({type:"media-source",audio:{contentType:Ft(g,"audio"),channels:""+d}})))}}))}),Promise.all(o.map(l=>{const c=rl(l);return sr[c]||(sr[c]=t.decodingInfo(l))})).then(l=>({supported:!l.some(c=>!c.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function rl(a){const{audio:e,video:t}=a,s=t||e;if(s){const i=s.contentType.split('"')[1];if(t)return`r${t.height}x${t.width}f${Math.ceil(t.framerate)}${t.transferFunction||"sd"}_${i}_${Math.ceil(t.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}function nl(){if(typeof matchMedia=="function"){const a=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(a.media!==e.media)return a.matches===!0}return!1}function al(a,e){let t=!1,s=[];return a&&(t=a!=="SDR",s=[a]),e&&(s=e.allowedVideoRanges||ls.slice(0),t=e.preferHDR!==void 0?e.preferHDR:nl(),t?s=s.filter(i=>i!=="SDR"):s=["SDR"]),{preferHDR:t,allowedVideoRanges:s}}function ol(a,e,t,s,i){const r=Object.keys(a),n=s?.channels,o=s?.audioCodec,l=n&&parseInt(n)===2;let c=!0,h=!1,u=1/0,d=1/0,g=1/0,f=0,m=[];const{preferHDR:E,allowedVideoRanges:T}=al(e,i);for(let x=r.length;x--;){const D=a[r[x]];c=D.channels[2]>0,u=Math.min(u,D.minHeight),d=Math.min(d,D.minFramerate),g=Math.min(g,D.minBitrate);const R=T.filter(C=>D.videoRanges[C]>0);R.length>0&&(h=!0,m=R)}u=N(u)?u:0,d=N(d)?d:0;const y=Math.max(1080,u),v=Math.max(30,d);return g=N(g)?g:t,t=Math.max(g,t),h||(e=void 0,m=[]),{codecSet:r.reduce((x,D)=>{const R=a[D];if(D===x)return x;if(R.minBitrate>t)return tt(D,`min bitrate of ${R.minBitrate} > current estimate of ${t}`),x;if(!R.hasDefaultAudio)return tt(D,"no renditions with default or auto-select sound found"),x;if(o&&D.indexOf(o.substring(0,4))%5!==0)return tt(D,`audio codec preference "${o}" not found`),x;if(n&&!l){if(!R.channels[n])return tt(D,`no renditions with ${n} channel sound found (channels options: ${Object.keys(R.channels)})`),x}else if((!o||l)&&c&&R.channels[2]===0)return tt(D,"no renditions with stereo sound found"),x;return R.minHeight>y?(tt(D,`min resolution of ${R.minHeight} > maximum of ${y}`),x):R.minFramerate>v?(tt(D,`min framerate of ${R.minFramerate} > maximum of ${v}`),x):m.some(C=>R.videoRanges[C]>0)?R.maxScore<f?(tt(D,`max score of ${R.maxScore} < selected max of ${f}`),x):x&&(as(D)>=as(x)||R.fragmentError>a[x].fragmentError)?x:(f=R.maxScore,D):(tt(D,`no variants with VIDEO-RANGE of ${JSON.stringify(m)} found`),x)},void 0),videoRanges:m,preferHDR:E,minFramerate:d,minBitrate:g}}function tt(a,e){S.log(`[abr] start candidates with "${a}" ignored because ${e}`)}function ll(a){return a.reduce((e,t)=>{let s=e.groups[t.groupId];s||(s=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),s.tracks.push(t);const i=t.channels||"2";return s.channels[i]=(s.channels[i]||0)+1,s.hasDefault=s.hasDefault||t.default,s.hasAutoSelect=s.hasAutoSelect||t.autoselect,s.hasDefault&&(e.hasDefaultAudio=!0),s.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function cl(a,e,t,s){return a.slice(t,s+1).reduce((i,r)=>{if(!r.codecSet)return i;const n=r.audioGroups;let o=i[r.codecSet];o||(i[r.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!n,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,r.bitrate);const l=Math.min(r.height,r.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,r.frameRate),o.maxScore=Math.max(o.maxScore,r.score),o.fragmentError+=r.fragmentError,o.videoRanges[r.videoRange]=(o.videoRanges[r.videoRange]||0)+1,n&&n.forEach(c=>{if(!c)return;const h=e.groups[c];h&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(h.channels).forEach(u=>{o.channels[u]=(o.channels[u]||0)+h.channels[u]}))}),i},{})}function Qe(a,e,t){if("attrs"in a){const s=e.indexOf(a);if(s!==-1)return s}for(let s=0;s<e.length;s++){const i=e[s];if(St(a,i,t))return s}return-1}function St(a,e,t){const{groupId:s,name:i,lang:r,assocLang:n,characteristics:o,default:l}=a,c=a.forced;return(s===void 0||e.groupId===s)&&(i===void 0||e.name===i)&&(r===void 0||e.lang===r)&&(r===void 0||e.assocLang===n)&&(l===void 0||e.default===l)&&(c===void 0||e.forced===c)&&(o===void 0||hl(o,e.characteristics))&&(t===void 0||t(a,e))}function hl(a,e=""){const t=a.split(","),s=e.split(",");return t.length===s.length&&!t.some(i=>s.indexOf(i)===-1)}function pt(a,e){const{audioCodec:t,channels:s}=a;return(t===void 0||(e.audioCodec||"").substring(0,4)===t.substring(0,4))&&(s===void 0||s===(e.channels||"2"))}function ul(a,e,t,s,i){const r=e[s],o=e.reduce((d,g,f)=>{const m=g.uri;return(d[m]||(d[m]=[])).push(f),d},{})[r.uri];o.length>1&&(s=Math.max.apply(Math,o));const l=r.videoRange,c=r.frameRate,h=r.codecSet.substring(0,4),u=ir(e,s,d=>{if(d.videoRange!==l||d.frameRate!==c||d.codecSet.substring(0,4)!==h)return!1;const g=d.audioGroups,f=t.filter(m=>!g||g.indexOf(m.groupId)!==-1);return Qe(a,f,i)>-1});return u>-1?u:ir(e,s,d=>{const g=d.audioGroups,f=t.filter(m=>!g||g.indexOf(m.groupId)!==-1);return Qe(a,f,i)>-1})}function ir(a,e,t){for(let s=e;s;s--)if(t(a[s]))return s;for(let s=e+1;s<a.length;s++)if(t(a[s]))return s;return-1}class dl{constructor(e){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this._abandonRulesCheck=()=>{const{fragCurrent:t,partCurrent:s,hls:i}=this,{autoLevelEnabled:r,media:n}=i;if(!t||!n)return;const o=performance.now(),l=s?s.stats:t.stats,c=s?s.duration:t.duration,h=o-l.loading.start,u=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||t.level<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!r||n.paused||!n.playbackRate||!n.readyState)return;const d=i.mainForwardBufferInfo;if(d===null)return;const g=this.bwEstimator.getEstimateTTFB(),f=Math.abs(n.playbackRate);if(h<=Math.max(g,1e3*(c/(f*2))))return;const m=d.len/f,E=l.loading.first?l.loading.first-l.loading.start:-1,T=l.loaded&&E>-1,y=this.getBwEstimate(),v=i.levels,A=v[t.level],x=l.total||Math.max(l.loaded,Math.round(c*A.averageBitrate/8));let D=T?h-E:h;D<1&&T&&(D=Math.min(h,l.loaded*8/y));const R=T?l.loaded*1e3/D:0,C=R?(x-l.loaded)/R:x*8/y+g/1e3;if(C<=m)return;const k=R?R*8:y;let I=Number.POSITIVE_INFINITY,w;for(w=t.level-1;w>u;w--){const F=v[w].maxBitrate;if(I=this.getTimeToLoadFrag(g/1e3,k,c*F,!v[w].details),I<m)break}if(I>=C||I>c*10)return;i.nextLoadLevel=i.nextAutoLevel=w,T?this.bwEstimator.sample(h-Math.min(g,E),l.loaded):this.bwEstimator.sampleTTFB(h);const B=v[w].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>B&&this.resetEstimator(B),this.clearTimer(),S.warn(`[abr] Fragment ${t.sn}${s?" part "+s.index:""} of level ${t.level} is loading too slowly;
2      Time to underbuffer: ${m.toFixed(3)} s
3      Estimated load time for current fragment: ${C.toFixed(3)} s
4      Estimated load time for down switch fragment: ${I.toFixed(3)} s
5      TTFB estimate: ${E|0} ms
6      Current BW estimate: ${N(y)?y|0:"Unknown"} bps
7      New BW estimate: ${this.getBwEstimate()|0} bps
8      Switching to level ${w} @ ${B|0} bps`),i.trigger(p.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:s,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(S.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new tl(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(p.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const s=t.frag;if(!this.ignoreFragment(s)){if(!s.bitrateTest){var i;this.fragCurrent=s,this.partCurrent=(i=t.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case b.BUFFER_ADD_CODEC_ERROR:case b.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case b.FRAG_LOAD_TIMEOUT:{const s=t.frag,{fragCurrent:i,partCurrent:r}=this;if(s&&i&&s.sn===i.sn&&s.level===i.level){const n=performance.now(),o=r?r.stats:s.stats,l=n-o.loading.start,c=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&c>-1){const u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(u,c),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,t,s,i){const r=e+s/t,n=i?this.lastLevelLoadSec:0;return r+n}onLevelLoaded(e,t){const s=this.hls.config,{loading:i}=t.stats,r=i.end-i.start;N(r)&&(this.lastLevelLoadSec=r/1e3),t.details.live?this.bwEstimator.update(s.abrEwmaSlowLive,s.abrEwmaFastLive):this.bwEstimator.update(s.abrEwmaSlowVoD,s.abrEwmaFastVoD)}onFragLoaded(e,{frag:t,part:s}){const i=s?s.stats:t.stats;if(t.type===H.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const r=s?s.duration:t.duration,n=this.hls.levels[t.level],o=(n.loaded?n.loaded.bytes:0)+i.loaded,l=(n.loaded?n.loaded.duration:0)+r;n.loaded={bytes:o,duration:l},n.realBitrate=Math.round(8*o/l)}if(t.bitrateTest){const r={stats:i,frag:t,part:s,id:t.type};this.onFragBuffered(p.FRAG_BUFFERED,r),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:s,part:i}=t,r=i!=null&&i.stats.loaded?i.stats:s.stats;if(r.aborted||this.ignoreFragment(s))return;const n=r.parsing.end-r.loading.start-Math.min(r.loading.first-r.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(n,r.loaded),r.bwEstimate=this.getBwEstimate(),s.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==H.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,s=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,r=this.findBestLevel(s,t,e,0,i,1,1);if(r>-1)return r;const n=this.hls.firstLevel,o=Math.min(Math.max(n,t),e);return S.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${n} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,s=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!s||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const r=s&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const n=this.hls.levels;if(n.length>Math.max(e,r)&&n[e].loadError<=n[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}
8_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:s}=this,{maxAutoLevel:i,config:r,minAutoLevel:n}=s,o=t?t.duration:e?e.duration:0,l=this.getBwEstimate(),c=this.getStarvationDelay();let h=r.abrBandWidthFactor,u=r.abrBandWidthUpFactor;if(c){const E=this.findBestLevel(l,n,i,c,0,h,u);if(E>=0)return E}let d=o?Math.min(o,r.maxStarvationDelay):r.maxStarvationDelay;if(!c){const E=this.bitrateTestDelay;E&&(d=(o?Math.min(o,r.maxLoadingDelay):r.maxLoadingDelay)-E,S.info(`[abr] bitrate test took ${Math.round(1e3*E)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),h=u=1)}const g=this.findBestLevel(l,n,i,c,d,h,u);if(S.info(`[abr] ${c?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`),g>-1)return g;const f=s.levels[n],m=s.levels[s.loadLevel];return f?.bitrate<m?.bitrate?n:s.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const s=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/s}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,s,i,r,n,o){var l;const c=i+r,h=this.lastLoadedFragLevel,u=h===-1?this.hls.firstLevel:h,{fragCurrent:d,partCurrent:g}=this,{levels:f,allAudioTracks:m,loadLevel:E,config:T}=this.hls;if(f.length===1)return 0;const y=f[u],v=!!(y!=null&&(l=y.details)!=null&&l.live),A=E===-1||h===-1;let x,D="SDR",R=y?.frameRate||0;const{audioPreference:C,videoPreference:k}=T,I=this.audioTracksByGroup||(this.audioTracksByGroup=ll(m));if(A){if(this.firstSelection!==-1)return this.firstSelection;const V=this.codecTiers||(this.codecTiers=cl(f,I,t,s)),U=ol(V,D,e,C,k),{codecSet:Z,videoRanges:q,minFramerate:O,minBitrate:M,preferHDR:ee}=U;x=Z,D=ee?q[q.length-1]:q[0],R=O,e=Math.max(e,M),S.log(`[abr] picked start tier ${JSON.stringify(U)}`)}else x=y?.codecSet,D=y?.videoRange;const w=g?g.duration:d?d.duration:0,B=this.bwEstimator.getEstimateTTFB()/1e3,F=[];for(let V=s;V>=t;V--){var G;const U=f[V],Z=V>u;if(!U)continue;if(T.useMediaCapabilities&&!U.supportedResult&&!U.supportedPromise){const ae=navigator.mediaCapabilities;typeof ae?.decodingInfo=="function"&&sl(U,I,D,R,e,C)?(U.supportedPromise=il(U,I,ae),U.supportedPromise.then(re=>{if(!this.hls)return;U.supportedResult=re;const de=this.hls.levels,Re=de.indexOf(U);re.error?S.warn(`[abr] MediaCapabilities decodingInfo error: "${re.error}" for level ${Re} ${JSON.stringify(re)}`):re.supported||(S.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Re} ${JSON.stringify(re)}`),Re>-1&&de.length>1&&(S.log(`[abr] Removing unsupported level ${Re}`),this.hls.removeLevel(Re)))})):U.supportedResult=cn}if(x&&U.codecSet!==x||D&&U.videoRange!==D||Z&&R>U.frameRate||!Z&&R>0&&R<U.frameRate||U.supportedResult&&!((G=U.supportedResult.decodingInfoResults)!=null&&G[0].smooth)){F.push(V);continue}const q=U.details,O=(g?q?.partTarget:q?.averagetargetduration)||w;let M;Z?M=o*e:M=n*e;const ee=w&&i>=w*2&&r===0?f[V].averageBitrate:f[V].maxBitrate,j=this.getTimeToLoadFrag(B,M,ee*O,q===void 0);if(M>=ee&&(V===h||U.loadError===0&&U.fragmentError===0)&&(j<=B||!N(j)||v&&!this.bitrateTestDelay||j<c)){const ae=this.forcedAutoLevel;return V!==E&&(ae===-1||ae!==E)&&(F.length&&S.trace(`[abr] Skipped level(s) ${F.join(",")} of ${s} max with CODECS and VIDEO-RANGE:"${f[F[0]].codecs}" ${f[F[0]].videoRange}; not compatible with "${y.codecs}" ${D}`),S.info(`[abr] switch candidate:${u}->${V} adjustedbw(${Math.round(M)})-bitrate=${Math.round(M-ee)} ttfb:${B.toFixed(1)} avgDuration:${O.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${j.toFixed(1)} firstSelection:${A} codecSet:${x} videoRange:${D} hls.loadLevel:${E}`)),A&&(this.firstSelection=V),V}}return-1}set nextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:s}=this.hls,i=Math.min(Math.max(e,s),t);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}}class fl{constructor(){this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}var xe={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class gl{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.BUFFER_APPENDED,this.onBufferAppended,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.BUFFER_APPENDED,this.onBufferAppended,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const s=this.activePartLists[t];if(s)for(let i=s.length;i--;){const r=s[i];if(!r)break;const n=r.end;if(r.start<=e&&n!==null&&e<=n)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){const{fragments:s}=this,i=Object.keys(s);for(let r=i.length;r--;){const n=s[i[r]];if(n?.body.type===t&&n.buffered){const o=n.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,t,s,i){this.timeRanges&&(this.timeRanges[e]=t);const r=i?.fragment.sn||-1;
vendor: 216,714 bytes, lines 8-26
8Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o||r>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===s&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(c=>{const h=!this.isTimeBuffered(c.startPTS,c.endPTS,t);return h&&this.removeFragment(o.body),h})})}detectPartialFragments(e){const t=this.timeRanges,{frag:s,part:i}=e;if(!t||s.sn==="initSegment")return;const r=Et(s),n=this.fragments[r];if(!n||n.buffered&&s.gap)return;const o=!s.relurl;Object.keys(t).forEach(l=>{const c=s.elementaryStreams[l];if(!c)return;const h=t[l],u=o||c.partial===!0;n.range[l]=this.getBufferedTimes(s,i,u,h)}),n.loaded=null,Object.keys(n.range).length?(n.buffered=!0,(n.body.endList=s.endList||n.body.endList)&&(this.endListFragments[n.body.type]=n),$t(n)||this.removeParts(s.sn-1,s.type)):this.removeFragment(n.body)}removeParts(e,t){const s=this.activePartLists[t];s&&(this.activePartLists[t]=s.filter(i=>i.fragment.sn>=e))}fragBuffered(e,t){const s=Et(e);let i=this.fragments[s];!i&&t&&(i=this.fragments[s]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,t,s,i){const r={time:[],partial:s},n=e.start,o=e.end,l=e.minEndPTS||o,c=e.maxStartPTS||n;for(let h=0;h<i.length;h++){const u=i.start(h)-this.bufferPadding,d=i.end(h)+this.bufferPadding;if(c>=u&&l<=d){r.time.push({startPTS:Math.max(n,i.start(h)),endPTS:Math.min(o,i.end(h))});break}else if(n<d&&o>u){const g=Math.max(n,i.start(h)),f=Math.min(o,i.end(h));f>g&&(r.partial=!0,r.time.push({startPTS:g,endPTS:f}))}else if(o<=u)break}return r}getPartialFragment(e){let t=null,s,i,r,n=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(c=>{const h=l[c];h&&$t(h)&&(i=h.body.start-o,r=h.body.end+o,e>=i&&e<=r&&(s=Math.min(e-i,r-e),n<=s&&(t=h.body,n=s)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||$t(t))}getState(e){const t=Et(e),s=this.fragments[t];return s?s.buffered?$t(s)?xe.PARTIAL:xe.OK:xe.APPENDING:xe.NOT_LOADED}isTimeBuffered(e,t,s){let i,r;for(let n=0;n<s.length;n++){if(i=s.start(n)-this.bufferPadding,r=s.end(n)+this.bufferPadding,e>=i&&t<=r)return!0;if(t<=i)return!1}return!1}onFragLoaded(e,t){const{frag:s,part:i}=t;if(s.sn==="initSegment"||s.bitrateTest)return;const r=i?null:t,n=Et(s);this.fragments[n]={body:s,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:s,part:i,timeRanges:r}=t;if(s.sn==="initSegment")return;const n=s.type;if(i){let o=this.activePartLists[n];o||(this.activePartLists[n]=o=[]),o.push(i)}this.timeRanges=r,Object.keys(r).forEach(o=>{const l=r[o];this.detectEvictedFragments(o,l,n,i)})}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Et(e);return!!this.fragments[t]}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,s,i,r){i&&!this.hasGaps||Object.keys(this.fragments).forEach(n=>{const o=this.fragments[n];if(!o)return;const l=o.body;l.type!==s||i&&!l.gap||l.start<t&&l.end>e&&(o.buffered||r)&&this.removeFragment(l)})}removeFragment(e){const t=Et(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const s=this.activePartLists[e.type];if(s){const i=e.sn;this.activePartLists[e.type]=s.filter(r=>r.fragment.sn!==i)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function $t(a){var e,t,s;return a.buffered&&(a.body.gap||((e=a.range.video)==null?void 0:e.partial)||((t=a.range.audio)==null?void 0:t.partial)||((s=a.range.audiovideo)==null?void 0:s.partial))}function Et(a){return`${a.type}_${a.level}_${a.sn}`}const ml={length:0,start:()=>0,end:()=>0};class ne{static isBuffered(e,t){try{if(e){const s=ne.getBuffered(e);for(let i=0;i<s.length;i++)if(t>=s.start(i)&&t<=s.end(i))return!0}}catch{}return!1}static bufferInfo(e,t,s){try{if(e){const i=ne.getBuffered(e),r=[];let n;for(n=0;n<i.length;n++)r.push({start:i.start(n),end:i.end(n)});return this.bufferedInfo(r,t,s)}}catch{}return{len:0,start:t,end:t,nextStart:void 0}}static bufferedInfo(e,t,s){t=Math.max(0,t),e.sort(function(c,h){const u=c.start-h.start;return u||h.end-c.end});let i=[];if(s)for(let c=0;c<e.length;c++){const h=i.length;if(h){const u=i[h-1].end;e[c].start-u<s?e[c].end>u&&(i[h-1].end=e[c].end):i.push(e[c])}else i.push(e[c])}else i=e;let r=0,n,o=t,l=t;for(let c=0;c<i.length;c++){const h=i[c].start,u=i[c].end;if(t+s>=h&&t<u)o=h,l=u,r=l-t;else if(t+s<h){n=h;break}}return{len:r,start:o||0,end:l||0,nextStart:n}}static getBuffered(e){try{return e.buffered}catch(t){return S.log("failed to get media.buffered",t),ml}}}class mi{constructor(e,t,s,i=0,r=-1,n=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=Kt(),this.buffering={audio:Kt(),video:Kt(),audiovideo:Kt()},this.level=e,this.sn=t,this.id=s,this.size=i,this.part=r,this.partial=n}}function Kt(){return{start:0,executeStart:0,executeEnd:0,end:0}}function Jt(a,e){for(let s=0,i=a.length;s<i;s++){var t;if(((t=a[s])==null?void 0:t.cc)===e)return a[s]}return null}function pl(a,e,t){return!!(e&&(t.endCC>t.startCC||a&&a.cc<t.startCC))}function El(a,e){const t=a.fragments,s=e.fragments;if(!s.length||!t.length){S.log("No fragments to align");return}const i=Jt(t,s[0].cc);if(!i||i&&!i.startPTS){S.log("No frag in previous level to align on");return}return i}function rr(a,e){if(a){const t=a.start+e;a.start=a.startPTS=t,a.endPTS=t+a.duration}}function hn(a,e){const t=e.fragments;for(let s=0,i=t.length;s<i;s++)rr(t[s],a);e.fragmentHint&&rr(e.fragmentHint,a),e.alignedSliding=!0}function Tl(a,e,t){e&&(yl(a,t,e),!t.alignedSliding&&e&&ds(t,e),!t.alignedSliding&&e&&!t.skippedSegments&&nn(e,t))}function yl(a,e,t){if(pl(a,t,e)){const s=El(t,e);s&&N(s.start)&&(S.log(`Adjusting PTS using last level due to CC increase within current level ${e.url}`),hn(s.start,e))}}function ds(a,e){if(!a.hasProgramDateTime||!e.hasProgramDateTime)return;const t=a.fragments,s=e.fragments;if(!t.length||!s.length)return;let i,r;const n=Math.min(e.endCC,a.endCC);e.startCC<n&&a.startCC<n&&(i=Jt(s,n),r=Jt(t,n)),(!i||!r)&&(i=s[Math.floor(s.length/2)],r=Jt(t,i.cc)||t[Math.floor(t.length/2)]);const o=i.programDateTime,l=r.programDateTime;if(!o||!l)return;const c=(l-o)/1e3-(r.start-i.start);hn(c,a)}const nr=Math.pow(2,17);class vl{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const s=e.url;if(!s)return Promise.reject(new it({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${s?"part list":"url"}`),networkDetails:null}));this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(g=>g[0]==="GAP")){l(or(e));return}else e.gap=!1;const c=this.loader=e.loader=r?new r(i):new n(i),h=ar(e),u=tr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:nr};e.stats=c.stats,c.load(h,d,{onSuccess:(g,f,m,E)=>{this.resetLoader(e,c);let T=g.data;m.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),o({frag:e,part:null,payload:T,networkDetails:E})},onError:(g,f,m,E)=>{this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Le({url:s,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:m,stats:E}))},onAbort:(g,f,m)=>{this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:m,stats:g}))},onTimeout:(g,f,m)=>{this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:g}))},onProgress:(g,f,m,E)=>{t&&t({frag:e,part:null,payload:m,networkDetails:E})}})})}loadPart(e,t,s){this.abort();const i=this.config,r=i.fLoader,n=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){l(or(e,t));return}const c=this.loader=e.loader=r?new r(i):new n(i),h=ar(e,t),u=tr(i.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:nr};t.stats=c.stats,c.load(h,d,{onSuccess:(g,f,m,E)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);const T={frag:e,part:t,payload:g.data,networkDetails:E};s(T),o(T)},onError:(g,f,m,E)=>{this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Le({url:h.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:m,stats:E}))},onAbort:(g,f,m)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:m,stats:g}))},onTimeout:(g,f,m)=>{this.resetLoader(e,c),l(new it({type:W.NETWORK_ERROR,details:b.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${d.timeout}ms`),networkDetails:m,stats:g}))}})})}updateStatsFromPart(e,t){const s=e.stats,i=t.stats,r=i.total;if(s.loaded+=i.loaded,r){const l=Math.round(e.duration/t.duration),c=Math.min(Math.round(s.loaded/r),l),u=(l-c)*Math.round(s.loaded/c);s.total=s.loaded+u}else s.total=Math.max(s.loaded,s.total);const n=s.loading,o=i.loading;n.start?n.first+=o.first-o.start:(n.start=o.start,n.first=o.first),n.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}}function ar(a,e=null){const t=e||a,s={frag:a,part:e,responseType:"arraybuffer",url:t.url,headers:{},rangeStart:0,rangeEnd:0},i=t.byteRangeStartOffset,r=t.byteRangeEndOffset;if(N(i)&&N(r)){var n;let o=i,l=r;if(a.sn==="initSegment"&&((n=a.decryptdata)==null?void 0:n.method)==="AES-128"){const c=r-i;c%16&&(l=r+(16-c%16)),i!==0&&(s.resetIV=!0,o=i-16)}s.rangeStart=o,s.rangeEnd=l}return s}function or(a,e){const t=new Error(`GAP ${a.gap?"tag":"attribute"} found`),s={type:W.MEDIA_ERROR,details:b.FRAG_GAP,fatal:!1,frag:a,error:t,networkDetails:null};return e&&(s.part=e),(e||a).stats.aborted=!0,new it(s)}class it extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class xl{constructor(e,t){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=t}decrypt(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)}}class Sl{constructor(e,t){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=t}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function Ll(a){const e=a.byteLength,t=e&&new DataView(a.buffer).getUint8(e-1);return t?ft(a,0,e-t):a}class Al{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),s=new Uint32Array(4);for(let i=0;i<4;i++)s[i]=t.getUint32(i*4);return s}initTable(){const e=this.sBox,t=this.invSBox,s=this.subMix,i=s[0],r=s[1],n=s[2],o=s[3],l=this.invSubMix,c=l[0],h=l[1],u=l[2],d=l[3],g=new Uint32Array(256);let f=0,m=0,E=0;for(E=0;E<256;E++)E<128?g[E]=E<<1:g[E]=E<<1^283;for(E=0;E<256;E++){let T=m^m<<1^m<<2^m<<3^m<<4;T=T>>>8^T&255^99,e[f]=T,t[T]=f;const y=g[f],v=g[y],A=g[v];let x=g[T]*257^T*16843008;i[f]=x<<24|x>>>8,r[f]=x<<16|x>>>16,n[f]=x<<8|x>>>24,o[f]=x,x=A*16843009^v*65537^y*257^f*16843008,c[T]=x<<24|x>>>8,h[T]=x<<16|x>>>16,u[T]=x<<8|x>>>24,d[T]=x,f?(f=y^g[g[g[A^y]]],m^=g[g[m]]):f=m=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let s=!0,i=0;for(;i<t.length&&s;)s=t[i]===this.key[i],i++;if(s)return;this.key=t;const r=this.keySize=t.length;if(r!==4&&r!==6&&r!==8)throw new Error("Invalid aes key size="+r);const n=this.ksRows=(r+6+1)*4;let o,l;const c=this.keySchedule=new Uint32Array(n),h=this.invKeySchedule=new Uint32Array(n),u=this.sBox,d=this.rcon,g=this.invSubMix,f=g[0],m=g[1],E=g[2],T=g[3];let y,v;for(o=0;o<n;o++){if(o<r){y=c[o]=t[o];continue}v=y,o%r===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/r|0]<<24):r>6&&o%r===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=y=(c[o-r]^v)>>>0}for(l=0;l<n;l++)o=n-l,l&3?v=c[o]:v=c[o-4],l<4||o<=4?h[l]=v:h[l]=f[u[v>>>24]]^m[u[v>>>16&255]]^E[u[v>>>8&255]]^T[u[v&255]],h[l]=h[l]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,s){const i=this.keySize+6,r=this.invKeySchedule,n=this.invSBox,o=this.invSubMix,l=o[0],c=o[1],h=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(s);let g=d[0],f=d[1],m=d[2],E=d[3];const T=new Int32Array(e),y=new Int32Array(T.length);let v,A,x,D,R,C,k,I,w,B,F,G,V,U;const Z=this.networkToHostOrderSwap;for(;t<T.length;){for(w=Z(T[t]),B=Z(T[t+1]),F=Z(T[t+2]),G=Z(T[t+3]),R=w^r[0],C=G^r[1],k=F^r[2],I=B^r[3],V=4,U=1;U<i;U++)v=l[R>>>24]^c[C>>16&255]^h[k>>8&255]^u[I&255]^r[V],A=l[C>>>24]^c[k>>16&255]^h[I>>8&255]^u[R&255]^r[V+1],x=l[k>>>24]^c[I>>16&255]^h[R>>8&255]^u[C&255]^r[V+2],D=l[I>>>24]^c[R>>16&255]^h[C>>8&255]^u[k&255]^r[V+3],R=v,C=A,k=x,I=D,V=V+4;v=n[R>>>24]<<24^n[C>>16&255]<<16^n[k>>8&255]<<8^n[I&255]^r[V],A=n[C>>>24]<<24^n[k>>16&255]<<16^n[I>>8&255]<<8^n[R&255]^r[V+1],x=n[k>>>24]<<24^n[I>>16&255]<<16^n[R>>8&255]<<8^n[C&255]^r[V+2],D=n[I>>>24]<<24^n[R>>16&255]<<16^n[C>>8&255]<<8^n[k&255]^r[V+3],y[t]=Z(v^g),y[t+1]=Z(D^f),y[t+2]=Z(x^m),y[t+3]=Z(A^E),g=w,f=B,m=F,E=G,t=t+4}return y.buffer}}const Rl=16;class pi{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.useSoftware=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const s=self.crypto;s&&(this.subtle=s.subtle||s.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const s=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?Ll(s):s}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,s){return this.useSoftware?new Promise((i,r)=>{this.softwareDecrypt(new Uint8Array(e),t,s);const n=this.flush();n?i(n.buffer):r(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,s)}softwareDecrypt(e,t,s){const{currentIV:i,currentResult:r,remainderData:n}=this;this.logOnce("JS AES decrypt"),n&&(e=He(n,e),this.remainderData=null);const o=this.getValidChunk(e);if(!o.length)return null;i&&(s=i);let l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Al),l.expandKey(t);const c=r;return this.currentResult=l.decrypt(o.buffer,0,s),this.currentIV=ft(o,-16).buffer,c||null}webCryptoDecrypt(e,t,s){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,s));this.key=t,this.fastAesKey=new Sl(this.subtle,t)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new xl(this.subtle,new Uint8Array(s)).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(S.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,s)))}onWebCryptoError(e,t,s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,s);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let t=e;const s=e.length-e.length%Rl;return s!==e.length&&(t=ft(e,0,s),this.remainderData=ft(e,s)),t}logOnce(e){this.logEnabled&&(S.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const bl={toString:function(a){let e="";const t=a.length;for(let s=0;s<t;s++)e+=`[${a.start(s).toFixed(3)}-${a.end(s).toFixed(3)}]`;return e}},_={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"};class Ei extends fl{constructor(e,t,s,i,r){super(),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=_.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.loadedmetadata=!1,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.onvseeking=null,this.onvended=null,this.logPrefix="",this.log=void 0,this.warn=void 0,this.playlistType=r,this.logPrefix=i,this.log=S.log.bind(S,`${i}:`),this.warn=S.warn.bind(S,`${i}:`),this.hls=e,this.fragmentLoader=new vl(e.config),this.keyLoader=s,this.fragmentTracker=t,this.config=e.config,this.decrypter=new pi(e.config),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=_.STOPPED}_streamEnded(e,t){if(t.live||e.nextStart||!e.end||!this.media)return!1;const s=t.partList;if(s!=null&&s.length){const r=s[s.length-1];return ne.isBuffered(this.media,r.start+r.duration/2)}const i=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(i)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null){var e;return(e=this.levelLastLoaded)==null?void 0:e.details}}onMediaAttached(e,t){const s=this.media=this.mediaBuffer=t.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),s.addEventListener("seeking",this.onvseeking),s.addEventListener("ended",this.onvended);const i=this.config;this.levels&&i.autoStartLoad&&this.state===_.STOPPED&&this.startLoad(i.startPosition)}onMediaDetaching(){const e=this.media;e!=null&&e.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&this.onvseeking&&this.onvended&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvended=null),this.keyLoader&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}onMediaSeeking(){const{config:e,fragCurrent:t,media:s,mediaBuffer:i,state:r}=this,n=s?s.currentTime:0,o=ne.bufferInfo(i||s,n,e.maxBufferHole);if(this.log(`media seeking to ${N(n)?n.toFixed(3):n}, state: ${r}`),this.state===_.ENDED)this.resetLoadingState();else if(t){const l=e.maxFragLookUpTolerance,c=t.start-l,h=t.start+t.duration+l;if(!o.len||h<o.start||c>o.end){const u=n>h;(n<c||u)&&(u&&t.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}s&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,this.playlistType,!0),this.lastCurrentTime=n),!this.loadedmetadata&&!o.len&&(this.nextLoadPosition=this.startPosition=n),this.tickImmediate()}onMediaEnded(){this.startPosition=this.lastCurrentTime=0}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset,this.initPTS=[]}onHandlerDestroying(){this.hls.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),this.stopLoad(),super.onHandlerDestroying(),this.hls=null}onHandlerDestroyed(){this.state=_.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,s){this._loadFragForPlayback(e,t,s)}_loadFragForPlayback(e,t,s){const i=r=>{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${r.part?" p: "+r.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(r)};this._doFragLoad(e,t,s,i).then(r=>{if(!r)return;const n=this.state;if(this.fragContextChanged(e)){(n===_.FRAG_LOADING||!this.fragCurrent&&n===_.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=_.IDLE);return}"payload"in r&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(p.FRAG_LOADED,r)),this._handleFragmentLoadComplete(r)}).catch(r=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(`Frag error: ${r?.message||r}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:s}=this;if(s.getState(e)===xe.APPENDING){const r=e.type,n=this.getFwdBufferInfo(this.mediaBuffer,r),o=Math.max(e.duration,n?n.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&s.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?s.removeAllFragments():s.hasParts(e.type)&&(s.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),s.getState(e)===xe.PARTIAL&&s.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,t,s=null){if(!(e-t))return;const i={startOffset:e,endOffset:t,type:s};this.hls.trigger(p.BUFFER_FLUSHING,i)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(s=>{if(!s||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return s}).then(s=>{const{hls:i}=this,{payload:r}=s,n=e.decryptdata;if(r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&n.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer).catch(l=>{throw i.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const c=self.performance.now();return i.trigger(p.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:c}}),s.payload=l,this.completeInitSegmentLoad(s)})}return this.completeInitSegmentLoad(s)}).catch(s=>{this.state===_.STOPPED||this.state===_.ERROR||(this.warn(s),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const s=e.frag.stats;this.state=_.IDLE,e.frag.data=new Uint8Array(e.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){var s,i,r,n;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.playlistType===H.MAIN?"level":"track"} ${e.level} (frag:[${((s=e.startPTS)!=null?s:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${o?bl.toString(ne.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==H.SUBTITLE){const h=e.elementaryStreams;if(!Object.keys(h).some(u=>!!h[u])){this.state=_.IDLE;return}}const c=(l=this.levels)==null?void 0:l[e.level];c!=null&&c.fragmentError&&(this.log(`Resetting level fragment error count of ${c.fragmentError} on frag buffered`),c.fragmentError=0)}this.state=_.IDLE,o&&(!this.loadedmetadata&&e.type==H.MAIN&&o.buffered.length&&((r=this.fragCurrent)==null?void 0:r.sn)===((n=this.fragPrevious)==null?void 0:n.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:s,part:i,partsLoaded:r}=e,n=!r||r.length===0||r.some(l=>!l),o=new mi(s.level,s.sn,s.stats.chunkCount+1,0,i?i.index:-1,!n);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,s=null,i){var r;const n=t?.details;if(!this.levels||!n)throw new Error(`frag load aborted, missing level${n?"":" detail"}s`);let o=null;if(e.encrypted&&!((r=e.decryptdata)!=null&&r.key)?(this.log(`Loading key for ${e.sn} of [${n.startSN}-${n.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=_.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(h=>{if(!this.fragContextChanged(h.frag))return this.hls.trigger(p.KEY_LOADED,h),this.state===_.KEY_LOADING&&(this.state=_.IDLE),h}),this.hls.trigger(p.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&n.encryptedFragments.length&&this.keyLoader.loadClear(e,n.encryptedFragments),s=Math.max(e.start,s||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const h=n.partList;if(h&&i){s>e.end&&n.fragmentHint&&(e=n.fragmentHint);const u=this.getNextPart(h,e,s);if(u>-1){const d=h[u];this.log(`Loading part sn: ${e.sn} p: ${d.index} cc: ${e.cc} of playlist [${n.startSN}-${n.endSN}] parts [0-${u}-${h.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),this.nextLoadPosition=d.start+d.duration,this.state=_.FRAG_LOADING;let g;return o?g=o.then(f=>!f||this.fragContextChanged(f.frag)?null:this.doFragPartsLoad(e,d,t,i)).catch(f=>this.handleFragLoadError(f)):g=this.doFragPartsLoad(e,d,t,i).catch(f=>this.handleFragLoadError(f)),this.hls.trigger(p.FRAG_LOADING,{frag:e,part:d,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):g}else if(!e.url||this.loadedEndOfParts(h,s))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${n?"of ["+n.startSN+"-"+n.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(s.toFixed(3))}`),N(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=_.FRAG_LOADING;const l=this.config.progressive;let c;return l&&o?c=o.then(h=>!h||this.fragContextChanged(h?.frag)?null:this.fragmentLoader.load(e,i)).catch(h=>this.handleFragLoadError(h)):c=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([h])=>(!l&&h&&i&&i(h),h)).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(p.FRAG_LOADING,{frag:e,targetBufferTime:s}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c}doFragPartsLoad(e,t,s,i){return new Promise((r,n)=>{var o;const l=[],c=(o=s.details)==null?void 0:o.partList,h=u=>{this.fragmentLoader.loadPart(e,u,i).then(d=>{l[u.index]=d;const g=d.part;this.hls.trigger(p.FRAG_LOADED,d);const f=Zi(s,e.sn,u.index+1)||an(c,e.sn,u.index+1);if(f)h(f);else return r({frag:e,part:g,partsLoaded:l})}).catch(n)};h(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;e.data&&t.details===b.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):this.hls.trigger(p.ERROR,t)}else this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==_.PARSING){!this.fragCurrent&&this.state!==_.STOPPED&&this.state!==_.ERROR&&(this.state=_.IDLE);return}const{frag:s,part:i,level:r}=t,n=self.performance.now();s.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(s,i,r,e.partial)}getCurrentContext(e){const{levels:t,fragCurrent:s}=this,{level:i,sn:r,part:n}=e;if(!(t!=null&&t[i]))return this.warn(`Levels object was unset while buffering fragment ${r} of level ${i}. The current chunk will not be buffered.`),null;const o=t[i],l=n>-1?Zi(o,r,n):null,c=l?l.fragment:zo(o,r,s);return c?(s&&s!==c&&(c.stats=s.stats),{frag:c,part:l,level:o}):null}bufferFragmentData(e,t,s,i,r){var n;if(!e||this.state!==_.PARSING)return;const{data1:o,data2:l}=e;let c=o;if(o&&l&&(c=He(o,l)),!((n=c)!=null&&n.length))return;const h={type:e.type,frag:t,part:s,chunkMeta:i,parent:t.type,data:c};if(this.hls.trigger(p.BUFFER_APPENDING,h),e.dropped&&e.independent&&!s){if(r)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!ne.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const s=t.currentTime,i=ne.bufferInfo(t,s,0),r=e.duration,n=Math.min(this.config.maxFragLookUpTolerance*2,r*.25),o=Math.max(Math.min(e.start-n,i.end-n),s+n);e.start-o>n&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){const s=this.getLoadPosition();return N(s)?this.getFwdBufferInfoAtPos(e,s,t):null}getFwdBufferInfoAtPos(e,t,s){const{config:{maxBufferHole:i}}=this,r=ne.bufferInfo(e,t,i);if(r.len===0&&r.nextStart!==void 0){const n=this.fragmentTracker.getBufferedFrag(t,s);if(n&&r.nextStart<n.end)return ne.bufferInfo(e,t,Math.max(r.nextStart,i))}return r}getMaxBufferLength(e){const{config:t}=this;let s;return e?s=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):s=t.maxBufferLength,Math.min(s,t.maxMaxBufferLength)}reduceMaxBufferLength(e,t){const s=this.config,i=Math.max(Math.min(e-t,s.maxBufferLength),t),r=Math.max(e-t*3,s.maxMaxBufferLength/2,i);return r>=i?(s.maxMaxBufferLength=r,this.warn(`Reduce max buffer length to ${r}s`),!0):!1}getAppendedFrag(e,t=H.MAIN){const s=this.fragmentTracker.getAppendedFrag(e,H.MAIN);return s&&"fragment"in s?s.fragment:s}getNextFragment(e,t){const s=t.fragments,i=s.length;if(!i)return null;const{config:r}=this,n=s[0].start;let o;if(t.live){const l=r.initialLiveManifestSize;if(i<l)return this.warn(`Not enough fragments to start playback (have: ${i}, need: ${l})`),null;(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<n)&&(o=this.getInitialLiveFragment(t,s),this.startPosition=this.nextLoadPosition=o?this.hls.liveSyncPosition||o.start:e)}else e<=n&&(o=s[0]);if(!o){const l=r.lowLatencyMode?t.partEnd:t.fragmentEnd;o=this.getFragmentAtPosition(e,l,t)}return this.mapToInitFragWhenRequired(o)}isLoopLoading(e,t){const s=this.fragmentTracker.getState(e);return(s===xe.OK||s===xe.PARTIAL&&!!e.gap)&&this.nextLoadPosition>t}getNextFragmentLoopLoading(e,t,s,i,r){const n=e.gap,o=this.getNextFragment(this.nextLoadPosition,t);if(o===null)return o;if(e=o,n&&e&&!e.gap&&s.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,s.nextStart,i);if(l!==null&&s.len+l.len>=r)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,s){let i=-1,r=!1,n=!0;for(let o=0,l=e.length;o<l;o++){const c=e[o];if(n=n&&!c.independent,i>-1&&s<c.start)break;const h=c.loaded;h?i=-1:(r||c.independent||n)&&c.fragment===t&&(i=o),r=h}return i}loadedEndOfParts(e,t){const s=e[e.length-1];return s&&t>s.start&&s.loaded}getInitialLiveFragment(e,t){const s=this.fragPrevious;let i=null;if(s){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${s.programDateTime}`),i=Xo(t,s.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const r=s.sn+1;if(r>=e.startSN&&r<=e.endSN){const n=t[r-e.startSN];s.cc===n.cc&&(i=n,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=Zo(t,s.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const r=this.hls.liveSyncPosition;r!==null&&(i=this.getFragmentAtPosition(r,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,t,s){const{config:i}=this;let{fragPrevious:r}=this,{fragments:n,endSN:o}=s;const{fragmentHint:l}=s,{maxFragLookUpTolerance:c}=i,h=s.partList,u=!!(i.lowLatencyMode&&h!=null&&h.length&&l);u&&l&&!this.bitrateTest&&(n=n.concat(l),o=l.sn);let d;if(e<t){const g=e>t-c?0:c;d=us(r,n,e,g)}else d=n[n.length-1];if(d){const g=d.sn-s.startSN,f=this.fragmentTracker.getState(d);if((f===xe.OK||f===xe.PARTIAL&&d.gap)&&(r=d),r&&d.sn===r.sn&&(!u||h[0].fragment.sn>d.sn)&&r&&d.level===r.level){const E=n[g+1];d.sn<o&&this.fragmentTracker.getState(E)!==xe.OK?d=E:d=null}}return d}synchronizeToLiveEdge(e){const{config:t,media:s}=this;if(!s)return;const i=this.hls.liveSyncPosition,r=s.currentTime,n=e.fragments[0].start,o=e.edge,l=r>=n-t.maxFragLookUpTolerance&&r<=o;if(i!==null&&s.duration>i&&(r<i||!l)){const c=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;(!l&&s.readyState<4||r<o-c)&&(this.loadedmetadata||(this.nextLoadPosition=i),s.readyState&&(this.warn(`Playback: ${r.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${i.toFixed(3)}`),s.currentTime=i))}}alignPlaylists(e,t,s){const i=e.fragments.length;if(!i)return this.warn("No fragments in live playlist"),0;const r=e.fragments[0].start,n=!t,o=e.alignedSliding&&N(r);if(n||!o&&!r){const{fragPrevious:l}=this;Tl(l,s,e);const c=e.fragments[0].start;return this.log(`Live playlist sliding: ${c.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),c}return r}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let s=this.startPosition;if(s<t&&(s=-1),s===-1||this.lastCurrentTime===-1){const i=this.startTimeOffset!==null,r=i?this.startTimeOffset:e.startTimeOffset;r!==null&&N(r)?(s=t+r,r<0&&(s+=e.totalduration),s=Math.min(Math.max(t,s),t+e.totalduration),this.log(`Start time offset ${r} found in ${i?"multivariant":"media"} playlist, adjust startPosition to ${s}`),this.startPosition=s):e.live?s=this.hls.liveSyncPosition||t:this.startPosition=s=0,this.lastCurrentTime=s}this.nextLoadPosition=s}getLoadPosition(){const{media:e}=this;let t=0;return this.loadedmetadata&&e?t=e.currentTime:this.nextLoadPosition&&(t=this.nextLoadPosition),t}handleFragLoadAborted(e,t){this.transmuxer&&e.sn!=="initSegment"&&e.stats.aborted&&(this.warn(`Fragment ${e.sn}${t?" part "+t.index:""} of level ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==_.FRAG_LOADING_WAITING_RETRY)&&(this.state=_.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){const h=this.getCurrentContext(t.chunkMeta);h&&(t.frag=h.frag)}const s=t.frag;if(!s||s.type!==e||!this.levels)return;if(this.fragContextChanged(s)){var i;this.warn(`Frag load error must match current frag to retry ${s.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const r=t.details===b.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(s,!0);const n=t.errorAction,{action:o,retryCount:l=0,retryConfig:c}=n||{};if(n&&o===Ae.RetryRequest&&c){this.resetStartWhenNotLoaded(this.levelLastLoaded);const h=fi(c,l);this.warn(`Fragment ${s.sn} of ${e} ${s.level} errored with ${t.details}, retrying loading ${l+1}/${c.maxNumRetry} in ${h}ms`),n.resolved=!0,this.retryDate=self.performance.now()+h,this.state=_.FRAG_LOADING_WAITING_RETRY}else if(c&&n)if(this.resetFragmentErrors(e),l<c.maxNumRetry)!r&&o!==Ae.RemoveAlternatePermanently&&(n.resolved=!0);else{S.warn(`${t.details} reached or exceeded max retry (${l})`);return}else n?.action===Ae.SendAlternateToPenaltyBox?this.state=_.WAITING_LEVEL:this.state=_.ERROR;this.tickImmediate()}reduceLengthAndFlushBuffer(e){if(this.state===_.PARSING||this.state===_.PARSED){const t=e.frag,s=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,s),r=i&&i.len>.5;r&&this.reduceMaxBufferLength(i.len,t?.duration||10);const n=!r;return n&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${s} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),n}return!1}resetFragmentErrors(e){e===H.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==_.STOPPED&&(this.state=_.IDLE)}afterBufferFlushed(e,t,s){if(!e)return;const i=ne.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,i,s),this.state===_.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=_.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const t=e?e.details:null;t!=null&&t.live?(this.startPosition=-1,this.setStartPosition(t,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,s,i){var r;const n=s.details;if(!n){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,c)=>{const h=e.elementaryStreams[c];if(h){const u=h.endPTS-h.startPTS;if(u<=0)return this.warn(`Could not parse fragment ${e.sn} ${c} duration reliably (${u})`),l||!1;const d=i?0:rn(n,e,h.startPTS,h.endPTS,h.startDTS,h.endDTS);return this.hls.trigger(p.LEVEL_PTS_UPDATED,{details:n,level:s,drift:d,type:c,frag:e,start:h.startPTS,end:h.endPTS}),!0}return l},!1)&&((r=this.transmuxer)==null?void 0:r.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(s.fragmentError===0&&(s.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${s.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=_.PARSED,this.hls.trigger(p.FRAG_PARSED,{frag:e,part:t})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}}class un{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let s;if(e.length)e.length===1?s=e[0]:s=Il(e,t);else return new Uint8Array(0);return this.reset(),s}reset(){this.chunks.length=0,this.dataLength=0}}function Il(a,e){const t=new Uint8Array(e);let s=0;for(let i=0;i<a.length;i++){const r=a[i];t.set(r,s),s+=r.length}return t}function Dl(){return typeof __HLS_WORKER_BUNDLE__=="function"}function Cl(){const a=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),e=self.URL.createObjectURL(a);return{worker:new self.Worker(e),objectURL:e}}function _l(a){const e=new self.URL(a,self.location.href).href;return{worker:new self.Worker(e),scriptURL:e}}function qe(a="",e=9e4){return{type:a,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}class Ti{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,s,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,s){}demux(e,t){this.cachedData&&(e=He(this.cachedData,e),this.cachedData=null);let s=kt(e,0),i=s?s.length:0,r;const n=this._audioTrack,o=this._id3Track,l=s?di(s):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&N(l))&&(this.basePTS=wl(l,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),s&&s.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ye.audioId3,duration:Number.POSITIVE_INFINITY});i<c;){if(this.canParse(e,i)){const h=this.appendFrame(n,e,i);h?(this.frameIndex++,this.lastPTS=h.sample.pts,i+=h.length,r=i):i=c}else Ja(e,i)?(s=kt(e,i),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:s,type:Ye.audioId3,duration:Number.POSITIVE_INFINITY}),i+=s.length,r=i):i++;if(i===c&&r!==c){const h=ft(e,r);this.cachedData?this.cachedData=He(this.cachedData,h):this.cachedData=h}}return{audioTrack:n,videoTrack:qe(),id3Track:o,textTrack:qe()}}demuxSampleAes(e,t,s){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:qe(),id3Track:this._id3Track,textTrack:qe()}}destroy(){}}const wl=(a,e,t)=>{if(N(a))return a*90;const s=t?t.baseTime*9e4/t.timescale:0;return e*9e4+s};function kl(a,e,t,s){let i,r,n,o;const l=navigator.userAgent.toLowerCase(),c=s,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[t+2]&192)>>>6)+1;const u=(e[t+2]&60)>>>2;if(u>h.length-1){const d=new Error(`invalid ADTS sampling index:${u}`);a.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!0,error:d,reason:d.message});return}return n=(e[t+2]&1)<<2,n|=(e[t+3]&192)>>>6,S.log(`manifest codec:${s}, ADTS type:${i}, samplingIndex:${u}`),/firefox/i.test(l)?u>=6?(i=5,o=new Array(4),r=u-3):(i=2,o=new Array(2),r=u):l.indexOf("android")!==-1?(i=2,o=new Array(2),r=u):(i=5,o=new Array(4),s&&(s.indexOf("mp4a.40.29")!==-1||s.indexOf("mp4a.40.5")!==-1)||!s&&u>=6?r=u-3:((s&&s.indexOf("mp4a.40.2")!==-1&&(u>=6&&n===1||/vivaldi/i.test(l))||!s&&n===1)&&(i=2,o=new Array(2)),r=u)),o[0]=i<<3,o[0]|=(u&14)>>1,o[1]|=(u&1)<<7,o[1]|=n<<3,i===5&&(o[1]|=(r&14)>>1,o[2]=(r&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[u],channelCount:n,codec:"mp4a.40."+i,manifestCodec:c}}function dn(a,e){return a[e]===255&&(a[e+1]&246)===240}function fn(a,e){return a[e+1]&1?7:9}function yi(a,e){return(a[e+3]&3)<<11|a[e+4]<<3|(a[e+5]&224)>>>5}function Pl(a,e){return e+5<a.length}function fs(a,e){return e+1<a.length&&dn(a,e)}function Fl(a,e){return Pl(a,e)&&dn(a,e)&&yi(a,e)<=a.length-e}function Ol(a,e){if(fs(a,e)){const t=fn(a,e);if(e+t>=a.length)return!1;const s=yi(a,e);if(s<=t)return!1;const i=e+s;return i===a.length||fs(a,i)}return!1}function gn(a,e,t,s,i){if(!a.samplerate){const r=kl(e,t,s,i);if(!r)return;a.config=r.config,a.samplerate=r.samplerate,a.channelCount=r.channelCount,a.codec=r.codec,a.manifestCodec=r.manifestCodec,S.log(`parsed codec:${a.codec}, rate:${r.samplerate}, channels:${r.channelCount}`)}}function mn(a){return 1024*9e4/a}function Ml(a,e){const t=fn(a,e);if(e+t<=a.length){const s=yi(a,e)-t;if(s>0)return{headerLength:t,frameLength:s}}}function pn(a,e,t,s,i){const r=mn(a.samplerate),n=s+i*r,o=Ml(e,t);let l;if(o){const{frameLength:u,headerLength:d}=o,g=d+u,f=Math.max(0,t+g-e.length);f?(l=new Uint8Array(g-d),l.set(e.subarray(t+d,e.length),0)):l=e.subarray(t+d,t+g);const m={unit:l,pts:n};return f||a.samples.push(m),{sample:m,length:g,missing:f}}const c=e.length-t;return l=new Uint8Array(c),l.set(e.subarray(t,e.length),0),{sample:{unit:l,pts:n},length:c,missing:-1}}let Ht=null;const Nl=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Ul=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Bl=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Gl=[0,1,1,4];function En(a,e,t,s,i){if(t+24>e.length)return;const r=Tn(e,t);if(r&&t+r.frameLength<=e.length){const n=r.samplesPerFrame*9e4/r.sampleRate,o=s+i*n,l={unit:e.subarray(t,t+r.frameLength),pts:o,dts:o};return a.config=[],a.channelCount=r.channelCount,a.samplerate=r.sampleRate,a.samples.push(l),{sample:l,length:r.frameLength,missing:0}}}function Tn(a,e){const t=a[e+1]>>3&3,s=a[e+1]>>1&3,i=a[e+2]>>4&15,r=a[e+2]>>2&3;if(t!==1&&i!==0&&i!==15&&r!==3){const n=a[e+2]>>1&1,o=a[e+3]>>6,l=t===3?3-s:s===3?3:4,c=Nl[l*14+i-1]*1e3,u=Ul[(t===3?0:t===2?1:2)*3+r],d=o===3?1:2,g=Bl[t][s],f=Gl[s],m=g*8*f,E=Math.floor(g*c/u+n)*f;if(Ht===null){const v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ht=v?parseInt(v[1]):0}return Ht&&Ht<=87&&s===2&&c>=224e3&&o===0&&(a[e+3]=a[e+3]|128),{sampleRate:u,channelCount:d,frameLength:E,samplesPerFrame:m}}}function vi(a,e){return a[e]===255&&(a[e+1]&224)===224&&(a[e+1]&6)!==0}function yn(a,e){return e+1<a.length&&vi(a,e)}function $l(a,e){return vi(a,e)&&4<=a.length-e}function vn(a,e){if(e+1<a.length&&vi(a,e)){const s=Tn(a,e);let i=4;s!=null&&s.frameLength&&(i=s.frameLength);const r=e+i;return r===a.length||yn(a,r)}return!1}class Kl extends Ti{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=kt(e,0);let s=t?.length||0;if(vn(e,s))return!1;for(let i=e.length;s<i;s++)if(Ol(e,s))return S.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Fl(e,t)}appendFrame(e,t,s){gn(e,this.observer,t,s,e.manifestCodec);const i=pn(e,t,s,this.basePTS,this.frameIndex);if(i&&i.missing===0)return i}}const Hl=/\/emsg[-/]ID3/i;class Vl{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,s,i){const r=this.videoTrack=qe("video",1),n=this.audioTrack=qe("audio",1),o=this.txtTrack=qe("text",1);if(this.id3Track=qe("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const l=qr(e);if(l.video){const{id:c,timescale:h,codec:u}=l.video;r.id=c,r.timescale=o.timescale=h,r.codec=u}if(l.audio){const{id:c,timescale:h,codec:u}=l.audio;n.id=c,n.timescale=h,n.codec=u}o.id=Yr.text,r.sampleDuration=0,r.duration=n.duration=i}resetContiguity(){this.remainderData=null}static probe(e){return oo(e)}demux(e,t){this.timeOffset=t;let s=e;const i=this.videoTrack,r=this.txtTrack;if(this.config.progressive){this.remainderData&&(s=He(this.remainderData,e));const o=po(s);this.remainderData=o.remainder,i.samples=o.valid||new Uint8Array}else i.samples=s;const n=this.extractID3Track(i,t);return r.samples=Fi(t,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:n,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,s=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const i=this.extractID3Track(t,this.timeOffset);return s.samples=Fi(e,t),{videoTrack:t,audioTrack:qe(),id3Track:i,textTrack:qe()}}extractID3Track(e,t){const s=this.id3Track;if(e.samples.length){const i=Q(e.samples,["emsg"]);i&&i.forEach(r=>{const n=yo(r);if(Hl.test(n.schemeIdUri)){const o=N(n.presentationTime)?n.presentationTime/n.timeScale:t+n.presentationTimeDelta/n.timeScale;let l=n.eventDuration===4294967295?Number.POSITIVE_INFINITY:n.eventDuration/n.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const c=n.payload;s.samples.push({data:c,len:c.byteLength,dts:o,pts:o,type:Ye.emsg,duration:l})}})}return s}demuxSampleAes(e,t,s){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const xn=(a,e)=>{let t=0,s=5;e+=s;const i=new Uint32Array(1),r=new Uint32Array(1),n=new Uint8Array(1);for(;s>0;){n[0]=a[e];const o=Math.min(s,8),l=8-o;r[0]=4278190080>>>24+l<<l,i[0]=(n[0]&r[0])>>l,t=t?t<<o|i[0]:i[0],e+=1,s-=o}return t};class Wl extends Ti{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,s){const i=Sn(e,t,s,this.basePTS,this.frameIndex);if(i!==-1)return{sample:e.samples[e.samples.length-1],length:i,missing:0}}static probe(e){if(!e)return!1;const t=kt(e,0);if(!t)return!1;const s=t.length;return e[s]===11&&e[s+1]===119&&di(t)!==void 0&&xn(e,s)<16}}function Sn(a,e,t,s,i){if(t+8>e.length||e[t]!==11||e[t+1]!==119)return-1;const r=e[t+4]>>6;if(r>=3)return-1;const o=[48e3,44100,32e3][r],l=e[t+4]&63,h=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+r]*2;if(t+h>e.length)return-1;const u=e[t+6]>>5;let d=0;u===2?d+=2:(u&1&&u!==1&&(d+=2),u&4&&(d+=2));const g=(e[t+6]<<8|e[t+7])>>12-d&1,m=[2,1,2,3,3,4,4,5][u]+g,E=e[t+5]>>3,T=e[t+5]&7,y=new Uint8Array([r<<6|E<<1|T>>2,(T&3)<<6|u<<3|g<<2|l>>4,l<<4&224]),v=1536/o*9e4,A=s+i*v,x=e.subarray(t,t+h);return a.config=y,a.channelCount=m,a.samplerate=o,a.samples.push({unit:x,pts:A}),h}class Yl{constructor(){this.VideoSample=null}createVideoSample(e,t,s,i){return{key:e,frame:!1,pts:t,dts:s,units:[],debug:i,length:0}}getLastNalUnit(e){var t;let s=this.VideoSample,i;if((!s||s.units.length===0)&&(s=e[e.length-1]),(t=s)!=null&&t.units){const r=s.units;i=r[r.length-1]}return i}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const s=t.samples,i=s.length;if(i){const r=s[i-1];e.pts=r.pts,e.dts=r.dts}else{t.dropped++;return}}t.samples.push(e)}e.debug.length&&S.log(e.pts+"/"+e.dts+":"+e.debug)}}class lr{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,s=e.byteLength-t,i=new Uint8Array(4),r=Math.min(4,t);if(r===0)throw new Error("no bytes available");i.set(e.subarray(s,s+r)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=r*8,this.bytesAvailable-=r}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const s=this.word>>>32-t;if(e>32&&S.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?s<<t|this.readBits(t):s}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}skipScalingList(e){let t=8,s=8,i;for(let r=0;r<e;r++)s!==0&&(i=this.readEG(),s=(t+i+256)%256),t=s===0?t:s}readSPS(){let e=0,t=0,s=0,i=0,r,n,o;const l=this.readUByte.bind(this),c=this.readBits.bind(this),h=this.readUEG.bind(this),u=this.readBoolean.bind(this),d=this.skipBits.bind(this),g=this.skipEG.bind(this),f=this.skipUEG.bind(this),m=this.skipScalingList.bind(this);l();const E=l();if(c(5),d(3),l(),f(),E===100||E===110||E===122||E===244||E===44||E===83||E===86||E===118||E===128){const D=h();if(D===3&&d(1),f(),f(),d(1),u())for(n=D!==3?8:12,o=0;o<n;o++)u()&&(o<6?m(16):m(64))}f();const T=h();if(T===0)h();else if(T===1)for(d(1),g(),g(),r=h(),o=0;o<r;o++)g();f(),d(1);const y=h(),v=h(),A=c(1);A===0&&d(1),d(1),u()&&(e=h(),t=h(),s=h(),i=h());let x=[1,1];if(u()&&u())switch(l()){case 1:x=[1,1];break;case 2:x=[12,11];break;case 3:x=[10,11];break;case 4:x=[16,11];break;case 5:x=[40,33];break;case 6:x=[24,11];break;case 7:x=[20,11];break;case 8:x=[32,11];break;case 9:x=[80,33];break;case 10:x=[18,11];break;case 11:x=[15,11];break;case 12:x=[64,33];break;case 13:x=[160,99];break;case 14:x=[4,3];break;case 15:x=[3,2];break;case 16:x=[2,1];break;case 255:{x=[l()<<8|l(),l()<<8|l()];break}}return{width:Math.ceil((y+1)*16-e*2-t*2),height:(2-A)*(v+1)*16-(A?2:4)*(s+i),pixelRatio:x}}readSliceType(){return this.readUByte(),this.readUEG(),this.readUEG()}}class jl extends Yl{parseAVCPES(e,t,s,i,r){const n=this.parseAVCNALu(e,s.data);let o=this.VideoSample,l,c=!1;s.data=null,o&&n.length&&!e.audFound&&(this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"")),n.forEach(h=>{var u;switch(h.type){case 1:{let m=!1;l=!0;const E=h.data;if(c&&E.length>4){const T=new lr(E).readSliceType();(T===2||T===4||T===7||T===9)&&(m=!0)}if(m){var d;(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.frame=!0,o.key=m;break}case 5:l=!0,(u=o)!=null&&u.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,s.pts,s.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,Qr(h.data,1,s.pts,t.samples);break}case 7:{var g,f;l=!0,c=!0;const m=h.data,T=new lr(m).readSPS();if(!e.sps||e.width!==T.width||e.height!==T.height||((g=e.pixelRatio)==null?void 0:g[0])!==T.pixelRatio[0]||((f=e.pixelRatio)==null?void 0:f[1])!==T.pixelRatio[1]){e.width=T.width,e.height=T.height,e.pixelRatio=T.pixelRatio,e.sps=[m],e.duration=r;const y=m.subarray(1,4);let v="avc1.";for(let A=0;A<3;A++){let x=y[A].toString(16);x.length<2&&(x="0"+x),v+=x}e.codec=v}break}case 8:l=!0,e.pps=[h.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,s.pts,s.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+h.type+" ");break}o&&l&&o.units.push(h)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,t){const s=t.byteLength;let i=e.naluState||0;const r=i,n=[];let o=0,l,c,h,u=-1,d=0;for(i===-1&&(u=0,d=t[0]&31,i=0,o=1);o<s;){if(l=t[o++],!i){i=l?0:1;continue}if(i===1){i=l?0:2;continue}if(!l)i=3;else if(l===1){if(c=o-i-1,u>=0){const g={data:t.subarray(u,c),type:d};n.push(g)}else{const g=this.getLastNalUnit(e.samples);g&&(r&&o<=4-r&&g.state&&(g.data=g.data.subarray(0,g.data.byteLength-r)),c>0&&(g.data=He(g.data,t.subarray(0,c)),g.state=0))}o<s?(h=t[o]&31,u=o,d=h,i=0):i=-1}else i=0}if(u>=0&&i>=0){const g={data:t.subarray(u,s),type:d,state:i};n.push(g)}if(n.length===0){const g=this.getLastNalUnit(e.samples);g&&(g.data=He(g.data,t))}return e.naluState=i,n}}class zl{constructor(e,t,s){this.keyData=void 0,this.decrypter=void 0,this.keyData=s,this.decrypter=new pi(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,t,s){const i=e[t].unit;if(i.length<=16)return;const r=i.subarray(16,i.length-i.length%16),n=r.buffer.slice(r.byteOffset,r.byteOffset+r.length);this.decryptBuffer(n).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,s)})}decryptAacSamples(e,t,s){for(;;t++){if(t>=e.length){s();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,s),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,s=new Int8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)s.set(e.subarray(r,r+16),i);return s}getAvcDecryptedUnit(e,t){const s=new Uint8Array(t);let i=0;for(let r=32;r<e.length-16;r+=160,i+=16)e.set(s.subarray(i,i+16),r);return e}decryptAvcSample(e,t,s,i,r){const n=Jr(r.data),o=this.getAvcEncryptedData(n);this.decryptBuffer(o.buffer).then(l=>{r.data=this.getAvcDecryptedUnit(n,l),this.decrypter.isSync()||this.decryptAvcSamples(e,t,s+1,i)})}decryptAvcSamples(e,t,s,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,s=0){if(t>=e.length){i();return}const r=e[t].units;for(;!(s>=r.length);s++){const n=r[s];if(!(n.data.length<=48||n.type!==1&&n.type!==5)&&(this.decryptAvcSample(e,t,s,i,n),!this.decrypter.isSync()))return}}}}const Ee=188;class ot{constructor(e,t,s){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.videoParser=new jl}static probe(e){const t=ot.syncOffset(e);return t>0&&S.warn(`MPEG2-TS detected but first sync word found @ offset ${t}`),t!==-1}static syncOffset(e){const t=e.length;let s=Math.min(Ee*5,t-Ee)+1,i=0;for(;i<s;){let r=!1,n=-1,o=0;for(let l=i;l<t;l+=Ee)if(e[l]===71&&(t-l===Ee||e[l+Ee]===71)){if(o++,n===-1&&(n=l,n!==0&&(s=Math.min(n+Ee*99,e.length-Ee)+1)),r||(r=Zs(e,l)===0),r&&o>1&&(n===0&&o>2||l+Ee>s))return n}else{if(o)return-1;break}i++}return-1}static createTrack(e,t){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:Yr[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?t:void 0}}resetInitSegment(e,t,s,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=ot.createTrack("video"),this._audioTrack=ot.createTrack("audio",i),this._id3Track=ot.createTrack("id3"),this._txtTrack=ot.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=t,this.videoCodec=s,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:t,_id3Track:s}=this;e&&(e.pesData=null),t&&(t.pesData=null),s&&(s.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,t,s=!1,i=!1){s||(this.sampleAes=null);let r;const n=this._videoTrack,o=this._audioTrack,l=this._id3Track,c=this._txtTrack;let h=n.pid,u=n.pesData,d=o.pid,g=l.pid,f=o.pesData,m=l.pesData,E=null,T=this.pmtParsed,y=this._pmtId,v=e.length;if(this.remainderData&&(e=He(this.remainderData,e),v=e.length,this.remainderData=null),v<Ee&&!i)return this.remainderData=e,{audioTrack:o,videoTrack:n,id3Track:l,textTrack:c};const A=Math.max(0,ot.syncOffset(e));v-=(v-A)%Ee,v<e.byteLength&&!i&&(this.remainderData=new Uint8Array(e.buffer,v,e.buffer.byteLength-v));let x=0;for(let R=A;R<v;R+=Ee)if(e[R]===71){const C=!!(e[R+1]&64),k=Zs(e,R),I=(e[R+3]&48)>>4;let w;if(I>1){if(w=R+5+e[R+4],w===R+Ee)continue}else w=R+4;switch(k){case h:C&&(u&&(r=Tt(u))&&this.videoParser.parseAVCPES(n,c,r,!1,this._duration),u={data:[],size:0}),u&&(u.data.push(e.subarray(w,R+Ee)),u.size+=R+Ee-w);break;case d:if(C){if(f&&(r=Tt(f)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,r);break;case"mp3":this.parseMPEGPES(o,r);break;case"ac3":this.parseAC3PES(o,r);break}f={data:[],size:0}}f&&(f.data.push(e.subarray(w,R+Ee)),f.size+=R+Ee-w);break;case g:C&&(m&&(r=Tt(m))&&this.parseID3PES(l,r),m={data:[],size:0}),m&&(m.data.push(e.subarray(w,R+Ee)),m.size+=R+Ee-w);break;case 0:C&&(w+=e[w]+1),y=this._pmtId=ql(e,w);break;case y:{C&&(w+=e[w]+1);const B=Xl(e,w,this.typeSupported,s,this.observer);h=B.videoPid,h>0&&(n.pid=h,n.segmentCodec=B.segmentVideoCodec),d=B.audioPid,d>0&&(o.pid=d,o.segmentCodec=B.segmentAudioCodec),g=B.id3Pid,g>0&&(l.pid=g),E!==null&&!T&&(S.warn(`MPEG-TS PMT found at ${R} after unknown PID '${E}'. Backtracking to sync byte @${A} to parse all TS packets.`),E=null,R=A-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=k;break}}else x++;x>0&&gs(this.observer,new Error(`Found ${x} TS packet/s that do not start with 0x47`)),n.pesData=u,o.pesData=f,l.pesData=m;const D={audioTrack:o,videoTrack:n,id3Track:l,textTrack:c};return i&&this.extractRemainingSamples(D),D}flush(){const{remainderData:e}=this;this.remainderData=null;let t;return e?t=this.demux(e,-1,!1,!0):t={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){const{audioTrack:t,videoTrack:s,id3Track:i,textTrack:r}=e,n=s.pesData,o=t.pesData,l=i.pesData;let c;if(n&&(c=Tt(n))?(this.videoParser.parseAVCPES(s,r,c,!0,this._duration),s.pesData=null):s.pesData=n,o&&(c=Tt(o))){switch(t.segmentCodec){case"aac":this.parseAACPES(t,c);break;case"mp3":this.parseMPEGPES(t,c);break;case"ac3":this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&S.log("last AAC PES packet truncated,might overlap between fragments"),t.pesData=o;l&&(c=Tt(l))?(this.parseID3PES(i,c),i.pesData=null):i.pesData=l}demuxSampleAes(e,t,s){const i=this.demux(e,s,!0,!this.config.progressive),r=this.sampleAes=new zl(this.observer,this.config,t);return this.decrypt(i,r)}decrypt(e,t){return new Promise(s=>{const{audioTrack:i,videoTrack:r}=e;i.samples&&i.segmentCodec==="aac"?t.decryptAacSamples(i.samples,0,()=>{r.samples?t.decryptAvcSamples(r.samples,0,0,()=>{s(e)}):s(e)}):r.samples&&t.decryptAvcSamples(r.samples,0,0,()=>{s(e)})})}destroy(){this._duration=0}parseAACPES(e,t){let s=0;const i=this.aacOverFlow;let r=t.data;if(i){this.aacOverFlow=null;const u=i.missing,d=i.sample.unit.byteLength;if(u===-1)r=He(i.sample.unit,r);else{const g=d-u;i.sample.unit.set(r.subarray(0,u),g),e.samples.push(i.sample),s=i.missing}}let n,o;for(n=s,o=r.length;n<o-1&&!fs(r,n);n++);if(n!==s){let u;const d=n<o-1;if(d?u=`AAC PES did not start with ADTS header,offset:${n}`:u="No ADTS header found in AAC PES",gs(this.observer,new Error(u),d),!d)return}gn(e,this.observer,r,n,this.audioCodec);let l;if(t.pts!==void 0)l=t.pts;else if(i){const u=mn(e.samplerate);l=i.sample.pts+u}else{S.warn("[tsdemuxer]: AAC PES unknown PTS");return}let c=0,h;for(;n<o;)if(h=pn(e,r,n,l,c),n+=h.length,h.missing){this.aacOverFlow=h;break}else for(c++;n<o-1&&!fs(r,n);n++);}parseMPEGPES(e,t){const s=t.data,i=s.length;let r=0,n=0;const o=t.pts;if(o===void 0){S.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;n<i;)if(yn(s,n)){const l=En(e,s,n,o,r);if(l)n+=l.length,r++;else break}else n++}parseAC3PES(e,t){{const s=t.data,i=t.pts;if(i===void 0){S.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const r=s.length;let n=0,o=0,l;for(;o<r&&(l=Sn(e,s,o,i,n++))>0;)o+=l}}parseID3PES(e,t){if(t.pts===void 0){S.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const s=me({},t,{type:this._videoTrack?Ye.emsg:Ye.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(s)}}function Zs(a,e){return((a[e+1]&31)<<8)+a[e+2]}function ql(a,e){return(a[e+10]&31)<<8|a[e+11]}function Xl(a,e,t,s,i){const r={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},n=(a[e+1]&15)<<8|a[e+2],o=e+3+n-4,l=(a[e+10]&15)<<8|a[e+11];for(e+=12+l;e<o;){const c=Zs(a,e),h=(a[e+3]&15)<<8|a[e+4];switch(a[e]){case 207:if(!s){ks("ADTS AAC");break}case 15:r.audioPid===-1&&(r.audioPid=c);break;case 21:r.id3Pid===-1&&(r.id3Pid=c);break;case 219:if(!s){ks("H.264");break}case 27:r.videoPid===-1&&(r.videoPid=c,r.segmentVideoCodec="avc");break;case 3:case 4:!t.mpeg&&!t.mp3?S.log("MPEG audio found, not supported in this browser"):r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="mp3");break;case 193:if(!s){ks("AC-3");break}case 129:t.ac3?r.audioPid===-1&&(r.audioPid=c,r.segmentAudioCodec="ac3"):S.log("AC-3 audio found, not supported in this browser");break;case 6:if(r.audioPid===-1&&h>0){let u=e+5,d=h;for(;d>2;){a[u]===106&&(t.ac3!==!0?S.log("AC-3 audio found, not supported in this browser for now"):(r.audioPid=c,r.segmentAudioCodec="ac3"));const f=a[u+1]+2;u+=f,d-=f}}break;case 194:case 135:return gs(i,new Error("Unsupported EC-3 in M2TS found")),r;case 36:return gs(i,new Error("Unsupported HEVC in M2TS found")),r}e+=h+5}return r}function gs(a,e,t){S.warn(`parsing error: ${e.message}`),a.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,levelRetry:t,error:e,reason:e.message})}function ks(a){S.log(`${a} with AES-128-CBC encryption found in unencrypted stream`)}function Tt(a){let e=0,t,s,i,r,n;const o=a.data;if(!a||a.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=He(o[0],o[1]),o.splice(1,1);if(t=o[0],(t[0]<<16)+(t[1]<<8)+t[2]===1){if(s=(t[4]<<8)+t[5],s&&s>a.size-6)return null;const c=t[7];c&192&&(r=(t[9]&14)*536870912+(t[10]&255)*4194304+(t[11]&254)*16384+(t[12]&255)*128+(t[13]&254)/2,c&64?(n=(t[14]&14)*536870912+(t[15]&255)*4194304+(t[16]&254)*16384+(t[17]&255)*128+(t[18]&254)/2,r-n>60*9e4&&(S.warn(`${Math.round((r-n)/9e4)}s delta between PTS and DTS, align them`),r=n)):n=r),i=t[8];let h=i+9;if(a.size<=h)return null;a.size-=h;const u=new Uint8Array(a.size);for(let d=0,g=o.length;d<g;d++){t=o[d];let f=t.byteLength;if(h)if(h>f){h-=f;continue}else t=t.subarray(h),f-=h,h=0;u.set(t,e),e+=f}return s&&(s-=i+3),{data:u,pts:r,dts:n,len:s}}return null}class Ql extends Ti{resetInitSegment(e,t,s,i){super.resetInitSegment(e,t,s,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=kt(e,0);let s=t?.length||0;if(t&&e[s]===11&&e[s+1]===119&&di(t)!==void 0&&xn(e,s)<=16)return!1;for(let i=e.length;s<i;s++)if(vn(e,s))return S.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return $l(e,t)}appendFrame(e,t,s){if(this.basePTS!==null)return En(e,t,s,this.basePTS,this.frameIndex)}}class cr{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const at=Math.pow(2,32)-1;class L{static init(){L.types={avc1:[],avcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let e;for(e in L.types)L.types.hasOwnProperty(e)&&(L.types[e]=[e.charCodeAt(0),e.charCodeAt(1),e.charCodeAt(2),e.charCodeAt(3)]);const t=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),s=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);L.HDLR_TYPES={video:t,audio:s};const i=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),r=new Uint8Array([0,0,0,0,0,0,0,0]);L.STTS=L.STSC=L.STCO=r,L.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),L.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),L.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),L.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),o=new Uint8Array([97,118,99,49]),l=new Uint8Array([0,0,0,1]);L.FTYP=L.box(L.types.ftyp,n,l,n,o),L.DINF=L.box(L.types.dinf,L.box(L.types.dref,i))}static box(e,...t){let s=8,i=t.length;const r=i;for(;i--;)s+=t[i].byteLength;const n=new Uint8Array(s);for(n[0]=s>>24&255,n[1]=s>>16&255,n[2]=s>>8&255,n[3]=s&255,n.set(e,4),i=0,s=8;i<r;i++)n.set(t[i],s),s+=t[i].byteLength;return n}static hdlr(e){return L.box(L.types.hdlr,L.HDLR_TYPES[e])}static mdat(e){return L.box(L.types.mdat,e)}static mdhd(e,t){t*=e;const s=Math.floor(t/(at+1)),i=Math.floor(t%(at+1));return L.box(L.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return L.box(L.types.mdia,L.mdhd(e.timescale,e.duration),L.hdlr(e.type),L.minf(e))}static mfhd(e){return L.box(L.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?L.box(L.types.minf,L.box(L.types.smhd,L.SMHD),L.DINF,L.stbl(e)):L.box(L.types.minf,L.box(L.types.vmhd,L.VMHD),L.DINF,L.stbl(e))}static moof(e,t,s){return L.box(L.types.moof,L.mfhd(e),L.traf(s,t))}static moov(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trak(e[t]);return L.box.apply(null,[L.types.moov,L.mvhd(e[0].timescale,e[0].duration)].concat(s).concat(L.mvex(e)))}static mvex(e){let t=e.length;const s=[];for(;t--;)s[t]=L.trex(e[t]);return L.box.apply(null,[L.types.mvex,...s])}static mvhd(e,t){t*=e;const s=Math.floor(t/(at+1)),i=Math.floor(t%(at+1)),r=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,s>>24,s>>16&255,s>>8&255,s&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return L.box(L.types.mvhd,r)}static sdtp(e){const t=e.samples||[],s=new Uint8Array(4+t.length);let i,r;for(i=0;i<t.length;i++)r=t[i].flags,s[i+4]=r.dependsOn<<4|r.isDependedOn<<2|r.hasRedundancy;return L.box(L.types.sdtp,s)}static stbl(e){return L.box(L.types.stbl,L.stsd(e),L.box(L.types.stts,L.STTS),L.box(L.types.stsc,L.STSC),L.box(L.types.stsz,L.STSZ),L.box(L.types.stco,L.STCO))}static avc1(e){let t=[],s=[],i,r,n;for(i=0;i<e.sps.length;i++)r=e.sps[i],n=r.byteLength,t.push(n>>>8&255),t.push(n&255),t=t.concat(Array.prototype.slice.call(r));for(i=0;i<e.pps.length;i++)r=e.pps[i],n=r.byteLength,s.push(n>>>8&255),s.push(n&255),s=s.concat(Array.prototype.slice.call(r));const o=L.box(L.types.avcC,new Uint8Array([1,t[3],t[4],t[5],255,224|e.sps.length].concat(t).concat([e.pps.length]).concat(s))),l=e.width,c=e.height,h=e.pixelRatio[0],u=e.pixelRatio[1];return L.box(L.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,c>>8&255,c&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,L.box(L.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),L.box(L.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,u>>24,u>>16&255,u>>8&255,u&255])))}static esds(e){const t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const t=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(e){return L.box(L.types.mp4a,L.audioStsd(e),L.box(L.types.esds,L.esds(e)))}static mp3(e){return L.box(L.types[".mp3"],L.audioStsd(e))}static ac3(e){return L.box(L.types["ac-3"],L.audioStsd(e),L.box(L.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?L.box(L.types.stsd,L.STSD,L.mp3(e)):e.segmentCodec==="ac3"?L.box(L.types.stsd,L.STSD,L.ac3(e)):L.box(L.types.stsd,L.STSD,L.mp4a(e)):L.box(L.types.stsd,L.STSD,L.avc1(e))}static tkhd(e){const t=e.id,s=e.duration*e.timescale,i=e.width,r=e.height,n=Math.floor(s/(at+1)),o=Math.floor(s%(at+1));return L.box(L.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,r>>8&255,r&255,0,0]))}static traf(e,t){const s=L.sdtp(e),i=e.id,r=Math.floor(t/(at+1)),n=Math.floor(t%(at+1));return L.box(L.types.traf,L.box(L.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),L.box(L.types.tfdt,new Uint8Array([1,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,n>>24,n>>16&255,n>>8&255,n&255])),L.trun(e,s.length+16+20+8+16+8+8),s)}static trak(e){return e.duration=e.duration||4294967295,L.box(L.types.trak,L.tkhd(e),L.mdia(e))}static trex(e){const t=e.id;return L.box(L.types.trex,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(e,t){const s=e.samples||[],i=s.length,r=12+16*i,n=new Uint8Array(r);let o,l,c,h,u,d;for(t+=8+r,n.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,t>>>24&255,t>>>16&255,t>>>8&255,t&255],0),o=0;o<i;o++)l=s[o],c=l.duration,h=l.size,u=l.flags,d=l.cts,n.set([c>>>24&255,c>>>16&255,c>>>8&255,c&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,u.isLeading<<2|u.dependsOn,u.isDependedOn<<6|u.hasRedundancy<<4|u.paddingValue<<1|u.isNonSync,u.degradPrio&61440,u.degradPrio&15,d>>>24&255,d>>>16&255,d>>>8&255,d&255],12+16*o);return L.box(L.types.trun,n)}static initSegment(e){L.types||L.init();const t=L.moov(e);return He(L.FTYP,t)}}L.types=void 0;L.HDLR_TYPES=void 0;L.STTS=void 0;L.STSC=void 0;L.STCO=void 0;L.STSZ=void 0;L.VMHD=void 0;L.SMHD=void 0;L.STSD=void 0;L.FTYP=void 0;L.DINF=void 0;const Ln=9e4;function xi(a,e,t=1,s=!1){const i=a*e*t;return s?Math.round(i):i}function Jl(a,e,t=1,s=!1){return xi(a,e,1/t,s)}function Dt(a,e=!1){return xi(a,1e3,1/Ln,e)}function Zl(a,e=1){return xi(a,Ln,1/e)}const ec=10*1e3,hr=1024,tc=1152,sc=1536;let yt=null,Ps=null;class Zt{constructor(e,t,s,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=s,this.ISGenerated=!1,yt===null){const n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);yt=n?parseInt(n[1]):0}if(Ps===null){const r=navigator.userAgent.match(/Safari\/(\d+)/i);Ps=r?parseInt(r[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){S.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){S.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){S.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const s=e.reduce((i,r)=>{const n=r.pts-i;return n<-4294967296?(t=!0,Ge(i,r.pts)):n>0?i:r.pts},e[0].pts);return t&&S.debug("PTS rollover detected"),s}remux(e,t,s,i,r,n,o,l){let c,h,u,d,g,f,m=r,E=r;const T=e.pid>-1,y=t.pid>-1,v=t.samples.length,A=e.samples.length>0,x=o&&v>0||v>1;if((!T||A)&&(!y||x)||this.ISGenerated||o){if(this.ISGenerated){var R,C,k,I;const G=this.videoTrackConfig;G&&(t.width!==G.width||t.height!==G.height||((R=t.pixelRatio)==null?void 0:R[0])!==((C=G.pixelRatio)==null?void 0:C[0])||((k=t.pixelRatio)==null?void 0:k[1])!==((I=G.pixelRatio)==null?void 0:I[1]))&&this.resetInitSegment()}else u=this.generateIS(e,t,r,n);const w=this.isVideoContiguous;let B=-1,F;if(x&&(B=ic(t.samples),!w&&this.config.forceKeyFrameOnDiscontinuity))if(f=!0,B>0){S.warn(`[mp4-remuxer]: Dropped ${B} out of ${v} video samples due to a missing keyframe`);const G=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(B),t.dropped+=B,E+=(t.samples[0].pts-G)/t.inputTimeScale,F=E}else B===-1&&(S.warn(`[mp4-remuxer]: No keyframe found out of ${v} video samples`),f=!1);if(this.ISGenerated){if(A&&x){const G=this.getVideoStartPts(t.samples),U=(Ge(e.samples[0].pts,G)-G)/t.inputTimeScale;m+=Math.max(0,U),E+=Math.max(0,-U)}if(A){if(e.samplerate||(S.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),u=this.generateIS(e,t,r,n)),h=this.remuxAudio(e,m,this.isAudioContiguous,n,y||x||l===H.AUDIO?E:void 0),x){const G=h?h.endPTS-h.startPTS:0;t.inputTimeScale||(S.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(e,t,r,n)),c=this.remuxVideo(t,E,w,G)}}else x&&(c=this.remuxVideo(t,E,w,0));c&&(c.firstKeyFrame=B,c.independent=B!==-1,c.firstKeyFramePTS=F)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(s.samples.length&&(g=An(s,r,this._initPTS,this._initDTS)),i.samples.length&&(d=Rn(i,r,this._initPTS))),{audio:h,video:c,initSegment:u,independent:f,text:d,id3:g}}generateIS(e,t,s,i){const r=e.samples,n=t.samples,o=this.typeSupported,l={},c=this._initPTS;let h=!c||i,u="audio/mp4",d,g,f;if(h&&(d=g=1/0),e.config&&r.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(u="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:u,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):L.initSegment([e]),metadata:{channelCount:e.channelCount}},h&&(f=e.inputTimeScale,!c||f!==c.timescale?d=g=r[0].pts-Math.round(f*s):h=!1)}if(t.sps&&t.pps&&n.length){if(t.timescale=t.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:L.initSegment([t]),metadata:{width:t.width,height:t.height}},h)if(f=t.inputTimeScale,!c||f!==c.timescale){const m=this.getVideoStartPts(n),E=Math.round(f*s);g=Math.min(g,Ge(n[0].dts,m)-E),d=Math.min(d,m-E)}else h=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,h?(this._initPTS={baseTime:d,timescale:f},this._initDTS={baseTime:g,timescale:f}):d=f=void 0,{tracks:l,initPTS:d,timescale:f}}remuxVideo(e,t,s,i){const r=e.inputTimeScale,n=e.samples,o=[],l=n.length,c=this._initPTS;let h=this.nextAvcDts,u=8,d=this.videoSampleDuration,g,f,m=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!s||h===null){const O=t*r,M=n[0].pts-Ge(n[0].dts,n[0].pts);yt&&h!==null&&Math.abs(O-M-h)<15e3?s=!0:h=O-M}const y=c.baseTime*r/c.timescale;for(let O=0;O<l;O++){const M=n[O];M.pts=Ge(M.pts-y,h),M.dts=Ge(M.dts-y,h),M.dts<n[O>0?O-1:O].dts&&(T=!0)}T&&n.sort(function(O,M){const ee=O.dts-M.dts,j=O.pts-M.pts;return ee||j}),g=n[0].dts,f=n[n.length-1].dts;const v=f-g,A=v?Math.round(v/(l-1)):d||e.inputTimeScale/30;if(s){const O=g-h,M=O>A,ee=O<-1;if((M||ee)&&(M?S.warn(`AVC: ${Dt(O,!0)} ms (${O}dts) hole between fragments detected at ${t.toFixed(3)}`):S.warn(`AVC: ${Dt(-O,!0)} ms (${O}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ee||h>=n[0].pts||yt)){g=h;const j=n[0].pts-O;if(M)n[0].dts=g,n[0].pts=j;else for(let X=0;X<n.length&&!(n[X].dts>j);X++)n[X].dts-=O,n[X].pts-=O;S.log(`Video: Initial PTS/DTS adjusted: ${Dt(j,!0)}/${Dt(g,!0)}, delta: ${Dt(O,!0)} ms`)}}g=Math.max(0,g);let x=0,D=0,R=g;for(let O=0;O<l;O++){const M=n[O],ee=M.units,j=ee.length;let X=0;for(let ae=0;ae<j;ae++)X+=ee[ae].data.length;D+=X,x+=j,M.length=X,M.dts<R?(M.dts=R,R+=A/4|0||1):R=M.dts,m=Math.min(M.pts,m),E=Math.max(M.pts,E)}f=n[l-1].dts;const C=D+4*x+8;let k;try{k=new Uint8Array(C)}catch(O){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:O,bytes:C,reason:`fail allocating video mdat ${C}`});return}const I=new DataView(k.buffer);I.setUint32(0,C),k.set(L.types.mdat,4);let w=!1,B=Number.POSITIVE_INFINITY,F=Number.POSITIVE_INFINITY,G=Number.NEGATIVE_INFINITY,V=Number.NEGATIVE_INFINITY;for(let O=0;O<l;O++){const M=n[O],ee=M.units;let j=0;for(let re=0,de=ee.length;re<de;re++){const Re=ee[re],Y=Re.data,$=Re.data.byteLength;I.setUint32(u,$),u+=4,k.set(Y,u),u+=$,j+=4+$}let X;if(O<l-1)d=n[O+1].dts-M.dts,X=n[O+1].pts-M.pts;else{const re=this.config,de=O>0?M.dts-n[O-1].dts:A;if(X=O>0?M.pts-n[O-1].pts:A,re.stretchShortVideoTrack&&this.nextAudioPts!==null){const Re=Math.floor(re.maxBufferHole*r),Y=(i?m+i*r:this.nextAudioPts)-M.pts;Y>Re?(d=Y-de,d<0?d=de:w=!0,S.log(`[mp4-remuxer]: It is approximately ${Y/90} ms to the next segment; using duration ${d/90} ms for the last video frame.`)):d=de}else d=de}const ae=Math.round(M.pts-M.dts);B=Math.min(B,d),G=Math.max(G,d),F=Math.min(F,X),V=Math.max(V,X),o.push(new ur(M.key,d,j,ae))}if(o.length){if(yt){if(yt<70){const O=o[0].flags;O.dependsOn=2,O.isNonSync=0}}else if(Ps&&V-F<G-B&&A/G<.025&&o[0].cts===0){S.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let O=g;for(let M=0,ee=o.length;M<ee;M++){const j=O+o[M].duration,X=O+o[M].cts;if(M<ee-1){const ae=j+o[M+1].cts;o[M].duration=ae-X}else o[M].duration=M?o[M-1].duration:A;o[M].cts=0,O=j}}}d=w||!d?A:d,this.nextAvcDts=h=f+d,this.videoSampleDuration=d,this.isVideoContiguous=!0;const q={data1:L.moof(e.sequenceNumber++,g,me({},e,{samples:o})),data2:k,startPTS:m/r,endPTS:(E+d)/r,startDTS:g/r,endDTS:h/r,type:"video",hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,q}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return tc;case"ac3":return sc;default:return hr}}remuxAudio(e,t,s,i,r){const n=e.inputTimeScale,o=e.samplerate?e.samplerate:n,l=n/o,c=this.getSamplesPerFrame(e),h=c*l,u=this._initPTS,d=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,g=[],f=r!==void 0;let m=e.samples,E=d?0:8,T=this.nextAudioPts||-1;const y=t*n,v=u.baseTime*n/u.timescale;if(this.isAudioContiguous=s=s||m.length&&T>0&&(i&&Math.abs(y-T)<9e3||Math.abs(Ge(m[0].pts-v,y)-T)<20*h),m.forEach(function(U){U.pts=Ge(U.pts-v,y)}),!s||T<0){if(m=m.filter(U=>U.pts>=0),!m.length)return;r===0?T=0:i&&!f?T=Math.max(0,y):T=m[0].pts}if(e.segmentCodec==="aac"){const U=this.config.maxAudioFramesDrift;for(let Z=0,q=T;Z<m.length;Z++){const O=m[Z],M=O.pts,ee=M-q,j=Math.abs(1e3*ee/n);if(ee<=-U*h&&f)Z===0&&(S.warn(`Audio frame @ ${(M/n).toFixed(3)}s overlaps nextAudioPts by ${Math.round(1e3*ee/n)} ms.`),this.nextAudioPts=T=q=M);else if(ee>=U*h&&j<ec&&f){let X=Math.round(ee/h);q=M-X*h,q<0&&(X--,q+=h),Z===0&&(this.nextAudioPts=T=q),S.warn(`[mp4-remuxer]: Injecting ${X} audio frame @ ${(q/n).toFixed(3)}s due to ${Math.round(1e3*ee/n)} ms gap.`);for(let ae=0;ae<X;ae++){const re=Math.max(q,0);let de=cr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);de||(S.log("[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead."),de=O.unit.subarray()),m.splice(Z,0,{unit:de,pts:re}),q+=h,Z++}}O.pts=q,q+=h}}let A=null,x=null,D,R=0,C=m.length;for(;C--;)R+=m[C].unit.byteLength;for(let U=0,Z=m.length;U<Z;U++){const q=m[U],O=q.unit;let M=q.pts;if(x!==null){const j=g[U-1];j.duration=Math.round((M-x)/l)}else if(s&&e.segmentCodec==="aac"&&(M=T),A=M,R>0){R+=E;try{D=new Uint8Array(R)}catch(j){this.observer.emit(p.ERROR,p.ERROR,{type:W.MUX_ERROR,details:b.REMUX_ALLOC_ERROR,fatal:!1,error:j,bytes:R,reason:`fail allocating audio mdat ${R}`});return}d||(new DataView(D.buffer).setUint32(0,R),D.set(L.types.mdat,4))}else return;D.set(O,E);const ee=O.byteLength;E+=ee,g.push(new ur(!0,c,ee,0)),x=M}const k=g.length;if(!k)return;const I=g[g.length-1];this.nextAudioPts=T=x+l*I.duration;const w=d?new Uint8Array(0):L.moof(e.sequenceNumber++,A/l,me({},e,{samples:g}));e.samples=[];const B=A/n,F=T/n,V={data1:w,data2:D,startPTS:B,endPTS:F,startDTS:B,endDTS:F,type:"audio",hasAudio:!0,hasVideo:!1,nb:k};return this.isAudioContiguous=!0,V}remuxEmptyAudio(e,t,s,i){const r=e.inputTimeScale,n=e.samplerate?e.samplerate:r,o=r/n,l=this.nextAudioPts,c=this._initDTS,h=c.baseTime*9e4/c.timescale,u=(l!==null?l:i.startDTS*r)+h,d=i.endDTS*r+h,g=o*hr,f=Math.ceil((d-u)/g),m=cr.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(S.warn("[mp4-remuxer]: remux empty Audio"),!m){S.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const E=[];for(let T=0;T<f;T++){const y=u+T*g;E.push({unit:m,pts:y,dts:y})}return e.samples=E,this.remuxAudio(e,t,s,!1)}}function Ge(a,e){let t;if(e===null)return a;for(e<a?t=-8589934592:t=8589934592;Math.abs(a-e)>4294967296;)a+=t;return a}function ic(a){for(let e=0;e<a.length;e++)if(a[e].key)return e;return-1}function An(a,e,t,s){const i=a.samples.length;if(!i)return;const r=a.inputTimeScale;for(let o=0;o<i;o++){const l=a.samples[o];l.pts=Ge(l.pts-t.baseTime*r/t.timescale,e*r)/r,l.dts=Ge(l.dts-s.baseTime*r/s.timescale,e*r)/r}const n=a.samples;return a.samples=[],{samples:n}}function Rn(a,e,t){const s=a.samples.length;if(!s)return;const i=a.inputTimeScale;for(let n=0;n<s;n++){const o=a.samples[n];o.pts=Ge(o.pts-t.baseTime*i/t.timescale,e*i)/i}a.samples.sort((n,o)=>n.pts-o.pts);const r=a.samples;return a.samples=[],{samples:r}}class ur{constructor(e,t,s,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=t,this.size=s,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class rc{constructor(){this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,t,s,i){this.audioCodec=t,this.videoCodec=s,this.generateInitSegment(ho(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:t,videoCodec:s}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=qr(e);i.audio&&(t=dr(i.audio,ie.AUDIO)),i.video&&(s=dr(i.video,ie.VIDEO));const r={};i.audio&&i.video?r.audiovideo={container:"video/mp4",codec:t+","+s,initSegment:e,id:"main"}:i.audio?r.audio={container:"audio/mp4",codec:t,initSegment:e,id:"audio"}:i.video?r.video={container:"video/mp4",codec:s,initSegment:e,id:"main"}:S.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=r}remux(e,t,s,i,r,n){var o,l;let{initPTS:c,lastEndTime:h}=this;const u={audio:void 0,video:void 0,text:i,id3:s,initSegment:void 0};N(h)||(h=this.lastEndTime=r||0);const d=t.samples;if(!(d!=null&&d.length))return u;const g={initPTS:void 0,timescale:1};let f=this.initData;if((o=f)!=null&&o.length||(this.generateInitSegment(d),f=this.initData),!((l=f)!=null&&l.length))return S.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),u;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const m=fo(d,f),E=uo(f,d),T=E===null?r:E;(nc(c,T,r,m)||g.timescale!==c.timescale&&n)&&(g.initPTS=T-r,c&&c.timescale===1&&S.warn(`Adjusting initPTS by ${g.initPTS-c.baseTime}`),this.initPTS=c={baseTime:g.initPTS,timescale:1});const y=e?T-c.baseTime/c.timescale:h,v=y+m;mo(f,d,c.baseTime/c.timescale),m>0?this.lastEndTime=v:(S.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const A=!!f.audio,x=!!f.video;let D="";A&&(D+="audio"),x&&(D+="video");const R={data1:d,startPTS:y,startDTS:y,endPTS:v,endDTS:v,type:D,hasAudio:A,hasVideo:x,nb:1,dropped:0};return u.audio=R.type==="audio"?R:void 0,u.video=R.type!=="audio"?R:void 0,u.initSegment=g,u.id3=An(s,r,c,c),i.samples.length&&(u.text=Rn(i,r,c)),u}}function nc(a,e,t,s){if(a===null)return!0;const i=Math.max(s,1),r=e-a.baseTime/a.timescale;return Math.abs(r-t)>i}function dr(a,e){const t=a?.codec;if(t&&t.length>4)return t;if(e===ie.AUDIO){if(t==="ec-3"||t==="ac-3"||t==="alac")return t;if(t==="fLaC"||t==="Opus")return os(t,!1);const s="mp4a.40.5";return S.info(`Parsed audio codec "${t}" or audio object type not handled. Using "${s}"`),s}return S.warn(`Unhandled video codec "${t}"`),t==="hvc1"||t==="hev1"?"hvc1.1.6.L120.90":t==="av01"?"av01.0.04M.08":"avc1.42e01e"}let rt;try{rt=self.performance.now.bind(self.performance)}catch{S.debug("Unable to use Performance API on this environment"),rt=At?.Date.now}const es=[{demux:Vl,remux:rc},{demux:ot,remux:Zt},{demux:Kl,remux:Zt},{demux:Ql,remux:Zt}];es.splice(2,0,{demux:Wl,remux:Zt});class fr{constructor(e,t,s,i,r){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=s,this.vendor=i,this.id=r}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,s,i){const r=s.transmuxing;r.executeStart=rt();let n=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:c,discontinuity:h,trackSwitch:u,accurateTimeOffset:d,timeOffset:g,initSegmentChange:f}=i||o,{audioCodec:m,videoCodec:E,defaultInitPts:T,duration:y,initSegmentData:v}=l,A=ac(n,t);if(A&&A.method==="AES-128"){const C=this.getDecrypter();if(C.isSync()){let k=C.softwareDecrypt(n,A.key.buffer,A.iv.buffer);if(s.part>-1&&(k=C.flush()),!k)return r.executeEnd=rt(),Fs(s);n=new Uint8Array(k)}else return this.decryptionPromise=C.webCryptoDecrypt(n,A.key.buffer,A.iv.buffer).then(k=>{const I=this.push(k,null,s);return this.decryptionPromise=null,I}),this.decryptionPromise}const x=this.needsProbing(h,u);if(x){const C=this.configureTransmuxer(n);if(C)return S.warn(`[transmuxer] ${C.message}`),this.observer.emit(p.ERROR,p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message}),r.executeEnd=rt(),Fs(s)}(h||u||f||x)&&this.resetInitSegment(v,m,E,y,t),(h||f||x)&&this.resetInitialTimestamp(T),c||this.resetContiguity();const D=this.transmux(n,A,g,d,s),R=this.currentTransmuxState;return R.contiguous=!0,R.discontinuity=!1,R.trackSwitch=!1,r.executeEnd=rt(),D}flush(e){const t=e.transmuxing;t.executeStart=rt();const{decrypter:s,currentTransmuxState:i,decryptionPromise:r}=this;if(r)return r.then(()=>this.flush(e));const n=[],{timeOffset:o}=i;if(s){const u=s.flush();u&&n.push(this.push(u,null,e))}const{demuxer:l,remuxer:c}=this;if(!l||!c)return t.executeEnd=rt(),[Fs(e)];const h=l.flush(o);return ts(h)?h.then(u=>(this.flushRemux(n,u,e),n)):(this.flushRemux(n,h,e),n)}flushRemux(e,t,s){const{audioTrack:i,videoTrack:r,id3Track:n,textTrack:o}=t,{accurateTimeOffset:l,timeOffset:c}=this.currentTransmuxState;S.log(`[transmuxer.ts]: Flushed fragment ${s.sn}${s.part>-1?" p: "+s.part:""} of level ${s.level}`);const h=this.remuxer.remux(i,r,n,o,c,l,!0,this.id);e.push({remuxResult:h,chunkMeta:s}),s.transmuxing.executeEnd=rt()}resetInitialTimestamp(e){const{demuxer:t,remuxer:s}=this;!t||!s||(t.resetTimeStamp(e),s.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,s,i,r){const{demuxer:n,remuxer:o}=this;!n||!o||(n.resetInitSegment(e,t,s,i),o.resetInitSegment(e,t,s,r))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,s,i,r){let n;return t&&t.method==="SAMPLE-AES"?n=this.transmuxSampleAes(e,t,s,i,r):n=this.transmuxUnencrypted(e,s,i,r),n}transmuxUnencrypted(e,t,s,i){const{audioTrack:r,videoTrack:n,id3Track:o,textTrack:l}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(r,n,o,l,t,s,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,t,s,i,r){return this.demuxer.demuxSampleAes(e,t,s).then(n=>({remuxResult:this.remuxer.remux(n.audioTrack,n.videoTrack,n.id3Track,n.textTrack,s,i,!1,this.id),chunkMeta:r}))}configureTransmuxer(e){const{config:t,observer:s,typeSupported:i,vendor:r}=this;let n;for(let d=0,g=es.length;d<g;d++){var o;if((o=es[d].demux)!=null&&o.probe(e)){n=es[d];break}}if(!n)return new Error("Failed to find demuxer by probing fragment data");const l=this.demuxer,c=this.remuxer,h=n.remux,u=n.demux;(!c||!(c instanceof h))&&(this.remuxer=new h(s,t,i,r)),(!l||!(l instanceof u))&&(this.demuxer=new u(s,t,i),this.probe=u.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new pi(this.config)),e}}function ac(a,e){let t=null;return a.byteLength>0&&e?.key!=null&&e.iv!==null&&e.method!=null&&(t=e),t}const Fs=a=>({remuxResult:{},chunkMeta:a});function ts(a){return"then"in a&&a.then instanceof Function}class oc{constructor(e,t,s,i,r){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=s,this.duration=i,this.defaultInitPts=r||null}}class lc{constructor(e,t,s,i,r,n){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=s,this.trackSwitch=i,this.timeOffset=r,this.initSegmentChange=n}}var bn={exports:{}};(function(a){var e=Object.prototype.hasOwnProperty,t="~";function s(){}Object.create&&(s.prototype=Object.create(null),new s().__proto__||(t=!1));function i(l,c,h){this.fn=l,this.context=c,this.once=h||!1}function r(l,c,h,u,d){if(typeof h!="function")throw new TypeError("The listener must be a function");var g=new i(h,u||l,d),f=t?t+c:c;return l._events[f]?l._events[f].fn?l._events[f]=[l._events[f],g]:l._events[f].push(g):(l._events[f]=g,l._eventsCount++),l}function n(l,c){--l._eventsCount===0?l._events=new s:delete l._events[c]}function o(){this._events=new s,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],h,u;if(this._eventsCount===0)return c;for(u in h=this._events)e.call(h,u)&&c.push(t?u.slice(1):u);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(h)):c},o.prototype.listeners=function(c){var h=t?t+c:c,u=this._events[h];if(!u)return[];if(u.fn)return[u.fn];for(var d=0,g=u.length,f=new Array(g);d<g;d++)f[d]=u[d].fn;return f},o.prototype.listenerCount=function(c){var h=t?t+c:c,u=this._events[h];return u?u.fn?1:u.length:0},o.prototype.emit=function(c,h,u,d,g,f){var m=t?t+c:c;if(!this._events[m])return!1;var E=this._events[m],T=arguments.length,y,v;if(E.fn){switch(E.once&&this.removeListener(c,E.fn,void 0,!0),T){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,h),!0;case 3:return E.fn.call(E.context,h,u),!0;case 4:return E.fn.call(E.context,h,u,d),!0;case 5:return E.fn.call(E.context,h,u,d,g),!0;case 6:return E.fn.call(E.context,h,u,d,g,f),!0}for(v=1,y=new Array(T-1);v<T;v++)y[v-1]=arguments[v];E.fn.apply(E.context,y)}else{var A=E.length,x;for(v=0;v<A;v++)switch(E[v].once&&this.removeListener(c,E[v].fn,void 0,!0),T){case 1:E[v].fn.call(E[v].context);break;case 2:E[v].fn.call(E[v].context,h);break;case 3:E[v].fn.call(E[v].context,h,u);break;case 4:E[v].fn.call(E[v].context,h,u,d);break;default:if(!y)for(x=1,y=new Array(T-1);x<T;x++)y[x-1]=arguments[x];E[v].fn.apply(E[v].context,y)}}return!0},o.prototype.on=function(c,h,u){return r(this,c,h,u,!1)},o.prototype.once=function(c,h,u){return r(this,c,h,u,!0)},o.prototype.removeListener=function(c,h,u,d){var g=t?t+c:c;if(!this._events[g])return this;if(!h)return n(this,g),this;var f=this._events[g];if(f.fn)f.fn===h&&(!d||f.once)&&(!u||f.context===u)&&n(this,g);else{for(var m=0,E=[],T=f.length;m<T;m++)(f[m].fn!==h||d&&!f[m].once||u&&f[m].context!==u)&&E.push(f[m]);E.length?this._events[g]=E.length===1?E[0]:E:n(this,g)}return this},o.prototype.removeAllListeners=function(c){var h;return c?(h=t?t+c:c,this._events[h]&&n(this,h)):(this._events=new s,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,a.exports=o})(bn);var cc=bn.exports,Si=wa(cc);class In{constructor(e,t,s,i){this.error=null,this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0;const r=e.config;this.hls=e,this.id=t,this.useWorker=!!r.enableWorker,this.onTransmuxComplete=s,this.onFlush=i;const n=(c,h)=>{h=h||{},h.frag=this.frag,h.id=this.id,c===p.ERROR&&(this.error=h.error),this.hls.trigger(c,h)};this.observer=new Si,this.observer.on(p.FRAG_DECRYPTED,n),this.observer.on(p.ERROR,n);const o=gt(r.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(r.workerPath||Dl())){try{r.workerPath?(S.log(`loading Web Worker ${r.workerPath} for "${t}"`),this.workerContext=_l(r.workerPath)):(S.log(`injecting Web Worker for "${t}"`),this.workerContext=Cl()),this.onwmsg=u=>this.onWorkerMessage(u);const{worker:h}=this.workerContext;h.addEventListener("message",this.onwmsg),h.onerror=u=>{const d=new Error(`${u.message}  (${u.filename}:${u.lineno})`);r.enableWorker=!1,S.warn(`Error in "${t}" Web Worker, fallback to inline`),this.hls.trigger(p.ERROR,{type:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})},h.postMessage({cmd:"init",typeSupported:l,vendor:"",id:t,config:JSON.stringify(r)})}catch(h){S.warn(`Error setting up "${t}" Web Worker, fallback to inline`,h),this.resetWorker(),this.error=null,this.transmuxer=new fr(this.observer,l,r,"",t)}return}this.transmuxer=new fr(this.observer,l,r,"",t)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:t}=this.workerContext;t&&self.URL.revokeObjectURL(t),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,t,s,i,r,n,o,l,c,h){var u,d;c.transmuxing.start=self.performance.now();const{transmuxer:g}=this,f=n?n.start:r.start,m=r.decryptdata,E=this.frag,T=!(E&&r.cc===E.cc),y=!(E&&c.level===E.level),v=E?c.sn-E.sn:-1,A=this.part?c.part-this.part.index:-1,x=v===0&&c.id>1&&c.id===E?.stats.chunkCount,D=!y&&(v===1||v===0&&(A===1||x&&A<=0)),R=self.performance.now();(y||v||r.stats.parsing.start===0)&&(r.stats.parsing.start=R),n&&(A||!D)&&(n.stats.parsing.start=R);const C=!(E&&((u=r.initSegment)==null?void 0:u.url)===((d=E.initSegment)==null?void 0:d.url)),k=new lc(T,D,l,y,f,C);if(!D||T||C){S.log(`[transmuxer-interface, ${r.type}]: Starting new transmux session for sn: ${c.sn} p: ${c.part} level: ${c.level} id: ${c.id}
9        discontinuity: ${T}
10        trackSwitch: ${y}
11        contiguous: ${D}
12        accurateTimeOffset: ${l}
13        timeOffset: ${f}
14        initSegmentChange: ${C}`);const I=new oc(s,i,t,o,h);this.configureTransmuxer(I)}if(this.frag=r,this.part=n,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:m,chunkMeta:c,state:k},e instanceof ArrayBuffer?[e]:[]);else if(g){const I=g.push(e,m,c,k);ts(I)?(g.async=!0,I.then(w=>{this.handleTransmuxComplete(w)}).catch(w=>{this.transmuxerError(w,c,"transmuxer-interface push error")})):(g.async=!1,this.handleTransmuxComplete(I))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:t}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(t){let s=t.flush(e);ts(s)||t.async?(ts(s)||(s=Promise.resolve(s)),s.then(r=>{this.handleFlushResult(r,e)}).catch(r=>{this.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(s,e)}}transmuxerError(e,t,s){this.hls&&(this.error=e,this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:s}))}handleFlushResult(e,t){e.forEach(s=>{this.handleTransmuxComplete(s)}),this.onFlush(t)}onWorkerMessage(e){const t=e.data;if(!(t!=null&&t.event)){S.warn(`worker message received with no ${t?"event name":"data"}`);return}const s=this.hls;if(this.hls)switch(t.event){case"init":{var i;const r=(i=this.workerContext)==null?void 0:i.objectURL;r&&self.URL.revokeObjectURL(r);break}case"transmuxComplete":{this.handleTransmuxComplete(t.data);break}case"flush":{this.onFlush(t.data);break}case"workerLog":S[t.data.logType]&&S[t.data.logType](t.data.message);break;default:{t.data=t.data||{},t.data.frag=this.frag,t.data.id=this.id,s.trigger(t.event,t.data);break}}}configureTransmuxer(e){const{transmuxer:t}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):t&&t.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function Dn(a,e){if(a.length!==e.length)return!1;for(let t=0;t<a.length;t++)if(!bt(a[t].attrs,e[t].attrs))return!1;return!0}function bt(a,e,t){const s=a["STABLE-RENDITION-ID"];return s&&!t?s===e["STABLE-RENDITION-ID"]:!(t||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(i=>a[i]!==e[i])}function ei(a,e){return e.label.toLowerCase()===a.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(a.lang||"").toLowerCase())}const gr=100;class hc extends Ei{constructor(e,t,s){super(e,t,s,"[audio-stream-controller]",H.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:t,id:s,initPTS:i,timescale:r}){if(s==="main"){const n=t.cc;this.initPTS[t.cc]={baseTime:i,timescale:r},this.log(`InitPTS for cc: ${n} found from main: ${i}`),this.videoTrackCC=n,this.state===_.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=_.STOPPED;return}const t=this.lastCurrentTime;this.stopLoad(),this.setInterval(gr),t>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${t.toFixed(3)}`),e=t,this.state=_.IDLE):(this.loadedmetadata=!1,this.state=_.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case _.IDLE:this.doTickIdle();break;case _.WAITING_TRACK:{var e;const{levels:s,trackId:i}=this,r=s==null||(e=s[i])==null?void 0:e.details;if(r){if(this.waitForCdnTuneIn(r))break;this.state=_.WAITING_INIT_PTS}break}case _.FRAG_LOADING_WAITING_RETRY:{var t;const s=performance.now(),i=this.retryDate;if(!i||s>=i||(t=this.media)!=null&&t.seeking){const{levels:r,trackId:n}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(r?.[n]||null),this.state=_.IDLE}break}case _.WAITING_INIT_PTS:{const s=this.waitingData;if(s){const{frag:i,part:r,cache:n,complete:o}=s;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=_.FRAG_LOADING;const l=n.flush(),c={frag:i,part:r,payload:l,networkDetails:null};this._handleFragmentLoadProgress(c),o&&super._handleFragmentLoadComplete(c)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),c=ne.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Js(c.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${c.end} is needed`),this.clearWaitingFragment())}}else this.state=_.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=_.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:t,media:s,trackId:i}=this,r=e.config;if(!s&&(this.startFragRequested||!r.startFragPrefetch)||!(t!=null&&t[i]))return;const n=t[i],o=n.details;if(!o||o.live&&this.levelLastLoaded!==n||this.waitForCdnTuneIn(o)){this.state=_.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,ie.AUDIO,H.AUDIO));const c=this.getFwdBufferInfo(l,H.AUDIO);if(c===null)return;const{bufferedTrack:h,switchingTrack:u}=this;if(!u&&this._streamEnded(c,o)){e.trigger(p.BUFFER_EOS,{type:"audio"}),this.state=_.ENDED;return}const d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,H.MAIN),g=c.len,f=this.getMaxBufferLength(d?.len),m=o.fragments,E=m[0].start;let T=this.flushing?this.getLoadPosition():c.end;if(u&&s){const x=this.getLoadPosition();h&&!bt(u.attrs,h.attrs)&&(T=x),o.PTSKnown&&x<E&&(c.end>E||c.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=E+.05)}if(g>=f&&!u&&T<m[m.length-1].start)return;let y=this.getNextFragment(T,o),v=!1;if(y&&this.isLoopLoading(y,T)&&(v=!!y.gap,y=this.getNextFragmentLoopLoading(y,o,c,H.MAIN,f)),!y){this.bufferFlushed=!0;return}const A=d&&y.start>d.end+o.targetduration;if(A||!(d!=null&&d.len)&&c.len){const x=this.getAppendedFrag(y.start,H.MAIN);if(x===null||(v||(v=!!x.gap||!!A&&d.len===0),A&&!v||v&&c.nextStart&&c.nextStart<x.end))return}this.loadFragment(y,n,T)}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.min(Math.max(t,e),this.config.maxMaxBufferLength):t}onMediaDetaching(){this.videoBuffer=null,this.bufferFlushed=this.flushing=!1,super.onMediaDetaching()}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(s=>new Rt(s))}onAudioTrackSwitching(e,t){const s=!!t.url;this.trackId=t.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),s?this.setInterval(gr):this.resetTransmuxer(),s?(this.switchingTrack=t,this.state=_.IDLE,this.flushAudioIfNeeded(t)):(this.switchingTrack=null,this.bufferedTrack=t,this.state=_.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,t){this.mainDetails=t.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(p.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,t){var s;if(this.mainDetails==null){this.cachedTrackLoadedData=t;return}const{levels:i}=this,{details:r,id:n}=t;if(!i){this.warn(`Audio tracks were reset while loading level ${n}`);return}this.log(`Audio track ${n} loaded [${r.startSN},${r.endSN}]${r.lastPartSn?`[part-${r.lastPartSn}-${r.lastPartIndex}]`:""},duration:${r.totalduration}`);const o=i[n];let l=0;if(r.live||(s=o.details)!=null&&s.live){this.checkLiveUpdate(r);const h=this.mainDetails;if(r.deltaUpdateFailed||!h)return;if(!o.details&&r.hasProgramDateTime&&h.hasProgramDateTime)ds(r,h),l=r.fragments[0].start;else{var c;l=this.alignPlaylists(r,o.details,(c=this.levelLastLoaded)==null?void 0:c.details)}}o.details=r,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!r.live)&&this.setStartPosition(this.mainDetails||r,l),this.state===_.WAITING_TRACK&&!this.waitForCdnTuneIn(r)&&(this.state=_.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{config:n,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${s.sn} of level ${s.level} will not be buffered`);return}const c=l[o];if(!c){this.warn("Audio track is undefined on fragment load progress");return}const h=c.details;if(!h){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(s.start);return}const u=n.defaultAudioCodec||c.audioCodec||"mp4a.40.2";let d=this.transmuxer;d||(d=this.transmuxer=new In(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[s.cc],f=(t=s.initSegment)==null?void 0:t.data;if(g!==void 0){const E=i?i.index:-1,T=E!==-1,y=new mi(s.level,s.sn,s.stats.chunkCount,r.byteLength,E,T);d.push(r,f,u,"",s,i,h.totalduration,!1,y,g)}else{this.log(`Unknown video PTS for cc ${s.cc}, waiting for video PTS before demuxing audio frag ${s.sn} of [${h.startSN} ,${h.endSN}],track ${o}`);const{cache:m}=this.waitingData=this.waitingData||{frag:s,part:i,cache:new un,complete:!1};m.push(new Uint8Array(r)),this.waitingVideoCC=this.videoTrackCC,this.state=_.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,t){const s=t.tracks.audio;s&&(this.mediaBuffer=s.buffer||null),t.tracks.video&&(this.videoBuffer=t.tracks.video.buffer||null)}onFragBuffered(e,t){const{frag:s,part:i}=t;if(s.type!==H.AUDIO){if(!this.loadedmetadata&&s.type===H.MAIN){const r=this.videoBuffer||this.media;r&&ne.getBuffered(r).length&&(this.loadedmetadata=!0)}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}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(s.sn!=="initSegment"){this.fragPrevious=s;const r=this.switchingTrack;r&&(this.bufferedTrack=r,this.switchingTrack=null,this.hls.trigger(p.AUDIO_TRACK_SWITCHED,Le({},r)))}this.fragBufferedComplete(s,i)}onError(e,t){var s;if(t.fatal){this.state=_.ERROR;return}switch(t.details){case b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,t);break;case b.AUDIO_TRACK_LOAD_ERROR:case b.AUDIO_TRACK_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_TRACK&&((s=t.context)==null?void 0:s.type)===te.AUDIO_TRACK&&(this.state=_.IDLE);break;case b.BUFFER_APPEND_ERROR:case b.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="audio")return;if(t.details===b.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==ie.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==ie.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===_.ENDED&&(this.state=_.IDLE);const s=this.mediaBuffer||this.media;s&&(this.afterBufferFlushed(s,t,H.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const s="audio",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:l,part:c,level:h}=o,{details:u}=h,{audio:d,text:g,id3:f,initSegment:m}=r;if(this.fragContextChanged(l)||!u){this.fragmentTracker.removeFragment(l);return}if(this.state=_.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){const E=l.initSegment||l;this._bufferInitSegment(h,m.tracks,E,n),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:s,tracks:m.tracks})}if(d){const{startPTS:E,endPTS:T,startDTS:y,endDTS:v}=d;c&&(c.elementaryStreams[ie.AUDIO]={startPTS:E,endPTS:T,startDTS:y,endDTS:v}),l.setElementaryStreamInfo(ie.AUDIO,E,T,y,v),this.bufferFragmentData(d,l,c,n)}if(f!=null&&(t=f.samples)!=null&&t.length){const E=me({id:s,frag:l,details:u},f);i.trigger(p.FRAG_PARSING_METADATA,E)}if(g){const E=me({id:s,frag:l,details:u},g);i.trigger(p.FRAG_PARSING_USERDATA,E)}}_bufferInitSegment(e,t,s,i){if(this.state!==_.PARSING)return;t.video&&delete t.video;const r=t.audio;if(!r)return;r.id="audio";const n=e.audioCodec;this.log(`Init audio buffer, container:${r.container}, codecs[level/parsed]=[${n}/${r.codec}]`),n&&n.split(",").length===1&&(r.levelCodec=n),this.hls.trigger(p.BUFFER_CODECS,t);const o=r.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:s,part:null,chunkMeta:i,parent:s.type,data:o};this.hls.trigger(p.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===xe.NOT_LOADED||i===xe.PARTIAL){var r;if(e.sn==="initSegment")this._loadInitSegment(e,t);else if((r=t.details)!=null&&r.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=_.WAITING_INIT_PTS;const n=this.mainDetails;n&&n.fragments[0].start!==t.details.fragments[0].start&&ds(t.details,n)}else this.startFragRequested=!0,super.loadFragment(e,t,s)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:t,bufferedTrack:s}=this,i=s?.attrs,r=e.attrs;t&&i&&(i.CHANNELS!==r.CHANNELS||s.name!==e.name||s.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(p.AUDIO_TRACK_SWITCHED,Le({},e))}}class uc extends gi{constructor(e){super(e,"[audio-track-controller]"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(p.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Audio track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Audio track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.audioGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(o=>i?.indexOf(o)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(d=>!s||s.indexOf(d.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(d=>d.default)&&(this.selectDefaultTrack=!1),o.forEach((d,g)=>{d.id=g});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!r&&l){const d=Qe(l,o,pt);if(d>-1)r=o[d];else{const g=Qe(l,this.tracks);r=this.tracks[g]}}let c=this.findTrackId(r);c===-1&&r&&(c=this.findTrackId(null));const h={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${s?.join(",")}`),this.hls.trigger(p.AUDIO_TRACKS_UPDATED,h);const u=this.trackId;if(c!==-1&&u===-1)this.setAudioTrack(c);else if(o.length&&u===-1){var n;const d=new Error(`No audio track selected for current audio group-ID(s): ${(n=this.groupIds)==null?void 0:n.join(",")} track count: ${o.length}`);this.warn(d.message),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:d})}}else this.shouldReloadPlaylist(r)&&this.setAudioTrack(this.trackId)}onError(e,t){t.fatal||!t.context||t.context.type===te.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(t))}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const s=this.allAudioTracks;if(this.selectDefaultTrack=!1,s.length){const i=this.currentTrack;if(i&&St(e,i,pt))return i;const r=Qe(e,this.tracksInGroup,pt);if(r>-1){const n=this.tracksInGroup[r];return this.setAudioTrack(r),n}else if(i){let n=t.loadLevel;n===-1&&(n=t.firstAutoLevel);const o=ul(e,t.levels,s,n,pt);if(o===-1)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){const n=Qe(e,s);if(n>-1)return s[n]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e],r=i.details&&!i.details.live;if(e===this.trackId&&i===s&&r||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(p.AUDIO_TRACK_SWITCHING,Le({},i)),r))return;const n=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(n)}findTrackId(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(!(this.selectDefaultTrack&&!i.default)&&(!e||St(e,i,pt)))return s}if(e){const{name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:l}=e;for(let c=0;c<t.length;c++){const h=t[c];if(St({name:s,lang:i,assocLang:r,characteristics:n,audioCodec:o,channels:l},h,pt))return c}for(let c=0;c<t.length;c++){const h=t[c];if(bt(e.attrs,h.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return c}for(let c=0;c<t.length;c++){const h=t[c];if(bt(e.attrs,h.attrs,["LANGUAGE"]))return c}}return-1}loadPlaylist(e){const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){super.loadPlaylist();const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}this.log(`loading audio-track playlist ${s} "${t.name}" lang:${t.lang} group:${i}`),this.clearTimer(),this.hls.trigger(p.AUDIO_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}}const mr=500;class dc extends Ei{constructor(e,t,s){super(e,t,s,"[subtitle-stream-controller]",H.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this._registerListeners()}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.ERROR,this.onError,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.ERROR,this.onError,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}startLoad(e){this.stopLoad(),this.state=_.IDLE,this.setInterval(mr),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}onManifestLoading(){this.mainDetails=null,this.fragmentTracker.removeAllFragments()}onMediaDetaching(){this.tracksBuffered=[],super.onMediaDetaching()}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:s,success:i}=t;if(this.fragPrevious=s,this.state=_.IDLE,!i)return;const r=this.tracksBuffered[this.currentTrackId];if(!r)return;let n;const o=s.start;for(let c=0;c<r.length;c++)if(o>=r[c].start&&o<=r[c].end){n=r[c];break}const l=s.start+s.duration;n?n.end=l:(n={start:o,end:l},r.push(n)),this.fragmentTracker.fragBuffered(s),this.fragBufferedComplete(s,null)}onBufferFlushing(e,t){const{startOffset:s,endOffset:i}=t;if(s===0&&i!==Number.POSITIVE_INFINITY){const r=i-1;if(r<=0)return;t.endOffsetSubtitles=Math.max(0,r),this.tracksBuffered.forEach(n=>{for(let o=0;o<n.length;){if(n[o].end<=r){n.shift();continue}else if(n[o].start<r)n[o].start=r;else break;o++}}),this.fragmentTracker.removeFragmentsInRange(s,r,H.SUBTITLE)}}onFragBuffered(e,t){if(!this.loadedmetadata&&t.frag.type===H.MAIN){var s;(s=this.media)!=null&&s.buffered.length&&(this.loadedmetadata=!0)}}onError(e,t){const s=t.frag;s?.type===H.SUBTITLE&&(t.details===b.FRAG_GAP&&this.fragmentTracker.fragBuffered(s,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==_.STOPPED&&(this.state=_.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Dn(this.levels,t)){this.levels=t.map(s=>new Rt(s));return}this.tracksBuffered=[],this.levels=t.map(s=>{const i=new Rt(s);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,H.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var s;if(this.currentTrackId=t.id,!((s=this.levels)!=null&&s.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(mr)}onSubtitleTrackLoaded(e,t){var s;const{currentTrackId:i,levels:r}=this,{details:n,id:o}=t;if(!r){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=r[o];if(o>=r.length||!l)return;this.log(`Subtitle track ${o} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""},duration:${n.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(n.live||(s=l.details)!=null&&s.live){const u=this.mainDetails;if(n.deltaUpdateFailed||!u)return;const d=u.fragments[0];if(!l.details)n.hasProgramDateTime&&u.hasProgramDateTime?(ds(n,u),c=n.fragments[0].start):d&&(c=d.start,Qs(n,c));else{var h;c=this.alignPlaylists(n,l.details,(h=this.levelLastLoaded)==null?void 0:h.details),c===0&&d&&(c=d.start,Qs(n,c))}}l.details=n,this.levelLastLoaded=l,o===i&&(!this.startFragRequested&&(this.mainDetails||!n.live)&&this.setStartPosition(this.mainDetails||n,c),this.tick(),n.live&&!this.fragCurrent&&this.media&&this.state===_.IDLE&&(us(null,n.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:s}=e,i=t.decryptdata,r=this.hls;if(!this.fragContextChanged(t)&&s&&s.byteLength>0&&i!=null&&i.key&&i.iv&&i.method==="AES-128"){const n=performance.now();this.decrypter.decrypt(new Uint8Array(s),i.key.buffer,i.iv.buffer).catch(o=>{throw r.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:t}),o}).then(o=>{const l=performance.now();r.trigger(p.FRAG_DECRYPTED,{frag:t,payload:o,stats:{tstart:n,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=_.IDLE})}}doTick(){if(!this.media){this.state=_.IDLE;return}if(this.state===_.IDLE){const{currentTrackId:e,levels:t}=this,s=t?.[e];if(!s||!t.length||!s.details)return;const{config:i}=this,r=this.getLoadPosition(),n=ne.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],r,i.maxBufferHole),{end:o,len:l}=n,c=this.getFwdBufferInfo(this.media,H.MAIN),h=s.details,u=this.getMaxBufferLength(c?.len)+h.levelTargetDuration;if(l>u)return;const d=h.fragments,g=d.length,f=h.edge;let m=null;const E=this.fragPrevious;if(o<f){const T=i.maxFragLookUpTolerance,y=o>f-T?0:T;m=us(E,d,Math.max(d[0].start,o),y),!m&&E&&E.start<d[0].start&&(m=d[0])}else m=d[g-1];if(!m)return;if(m=this.mapToInitFragWhenRequired(m),m.sn!=="initSegment"){const T=m.sn-h.startSN,y=d[T-1];y&&y.cc===m.cc&&this.fragmentTracker.getState(y)===xe.NOT_LOADED&&(m=y)}this.fragmentTracker.getState(m)===xe.NOT_LOADED&&this.loadFragment(m,s,o)}}getMaxBufferLength(e){const t=super.getMaxBufferLength();return e?Math.max(t,e):t}loadFragment(e,t,s){this.fragCurrent=e,e.sn==="initSegment"?this._loadInitSegment(e,t):(this.startFragRequested=!0,super.loadFragment(e,t,s))}get mediaBufferTimeRanges(){return new fc(this.tracksBuffered[this.currentTrackId]||[])}}class fc{constructor(e){this.buffered=void 0;const t=(s,i,r)=>{if(i=i>>>0,i>r-1)throw new DOMException(`Failed to execute '${s}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${r})`);return e[i][s]};this.buffered={get length(){return e.length},end(s){return t("end",s,e.length)},start(s){return t("start",s,e.length)}}}}class gc extends gi{constructor(e){super(e,"[subtitle-track-controller]"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const s=Xt(this.media.textTracks);for(let r=0;r<s.length;r++)if(s[r].mode==="hidden")t=s[r];else if(s[r].mode==="showing"){t=s[r];break}const i=this.findTrackForTextTrack(t);this.subtitleTrack!==i&&this.setSubtitleTrack(i)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(p.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADING,this.onLevelLoading,this),e.off(p.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(p.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(p.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Xt(this.media.textTracks).forEach(t=>{vt(t)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:s,groupId:i,details:r}=t,n=this.tracksInGroup[s];if(!n||n.groupId!==i){this.warn(`Subtitle track with id:${s} and group:${i} not found in active group ${n?.groupId}`);return}const o=n.details;n.details=t.details,this.log(`Subtitle track ${s} "${n.name}" lang:${n.lang} group:${i} loaded [${r.startSN}-${r.endSN}]`),s===this.trackId&&this.playlistLoaded(s,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const s=t.subtitleGroups||null,i=this.groupIds;let r=this.currentTrack;if(!s||i?.length!==s?.length||s!=null&&s.some(n=>i?.indexOf(n)===-1)){this.groupIds=s,this.trackId=-1,this.currentTrack=null;const n=this.tracks.filter(h=>!s||s.indexOf(h.groupId)!==-1);if(n.length)this.selectDefaultTrack&&!n.some(h=>h.default)&&(this.selectDefaultTrack=!1),n.forEach((h,u)=>{h.id=u});else if(!r&&!this.tracksInGroup.length)return;this.tracksInGroup=n;const o=this.hls.config.subtitlePreference;if(!r&&o){this.selectDefaultTrack=!1;const h=Qe(o,n);if(h>-1)r=n[h];else{const u=Qe(o,this.tracks);r=this.tracks[u]}}let l=this.findTrackId(r);l===-1&&r&&(l=this.findTrackId(null));const c={subtitleTracks:n};this.log(`Updating subtitle tracks, ${n.length} track(s) found in "${s?.join(",")}" group-id`),this.hls.trigger(p.SUBTITLE_TRACKS_UPDATED,c),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(r)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const t=this.tracksInGroup,s=this.selectDefaultTrack;for(let i=0;i<t.length;i++){const r=t[i];if(!(s&&!r.default||!s&&!e)&&(!e||St(r,e)))return i}if(e){for(let i=0;i<t.length;i++){const r=t[i];if(bt(e.attrs,r.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return i}for(let i=0;i<t.length;i++){const r=t[i];if(bt(e.attrs,r.attrs,["LANGUAGE"]))return i}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let s=0;s<t.length;s++){const i=t[s];if(ei(i,e))return s}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===te.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const s=this.currentTrack;if(s&&St(e,s))return s;const i=Qe(e,this.tracksInGroup);if(i>-1){const r=this.tracksInGroup[i];return this.setSubtitleTrack(i),r}else{if(s)return null;{const r=Qe(e,t);if(r>-1)return t[r]}}}}return null}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;if(this.shouldLoadPlaylist(t)&&t){const s=t.id,i=t.groupId;let r=t.url;if(e)try{r=e.addDirectives(r)}catch(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}this.log(`Loading subtitle playlist for id ${s}`),this.hls.trigger(p.SUBTITLE_TRACK_LOADING,{url:r,id:s,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Xt(e.textTracks),s=this.currentTrack;let i;if(s&&(i=t.filter(r=>ei(s,r))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${s.name}" and language "${s.lang}"`)),[].slice.call(t).forEach(r=>{r.mode!=="disabled"&&r!==i&&(r.mode="disabled")}),i){const r=this.subtitleDisplay?"showing":"hidden";i.mode!==r&&(i.mode=r)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!N(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const s=this.currentTrack,i=t[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:e});return}const r=!!i.details&&!i.details.live;if(e===this.trackId&&i===s&&r)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:n,groupId:o="",name:l,type:c,url:h}=i;this.hls.trigger(p.SUBTITLE_TRACK_SWITCH,{id:n,groupId:o,name:l,type:c,url:h});const u=this.switchParams(i.url,s?.details,i.details);this.loadPlaylist(u)}}class mc{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,t,s){const i=this.queues[t];i.push(e),i.length===1&&!s&&this.executeNext(t)}insertAbort(e,t){this.queues[t].unshift(e),this.executeNext(t)}appendBlocker(e){let t;const s=new Promise(r=>{t=r}),i={execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),s}executeNext(e){const t=this.queues[e];if(t.length){const s=t[0];try{s.execute()}catch(i){S.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${i}`),s.onError(i);const r=this.buffers[e];r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const pr=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class pc{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=s=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=s=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:s,mediaSource:i}=this;this.log("Media source opened"),s&&(s.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(p.MEDIA_ATTACHED,{media:s,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:s,_objectUrl:i}=this;s!==i&&S.error(`Media element src was set while attaching MediaSource (${i} > ${s})`)},this.hls=e;const t="[buffer-controller]";this.appendSource=Ro(gt(e.config.preferManagedMediaSource)),this.log=S.log.bind(S,t),this.warn=S.warn.bind(S,t),this.error=S.error.bind(S,t),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.BUFFER_RESET,this.onBufferReset,this),e.on(p.BUFFER_APPENDING,this.onBufferAppending,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.BUFFER_EOS,this.onBufferEos,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(p.FRAG_PARSED,this.onFragParsed,this),e.on(p.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.BUFFER_RESET,this.onBufferReset,this),e.off(p.BUFFER_APPENDING,this.onBufferAppending,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.BUFFER_EOS,this.onBufferEos,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(p.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(p.FRAG_PARSED,this.onFragParsed,this),e.off(p.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new mc(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){let s=2;(t.audio&&!t.video||!t.altAudio)&&(s=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=s,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,t){const s=this.media=t.media,i=gt(this.appendSource);if(s&&i){var r;const n=this.mediaSource=new i;this.log(`created media source: ${(r=n.constructor)==null?void 0:r.name}`),n.addEventListener("sourceopen",this._onMediaSourceOpen),n.addEventListener("sourceended",this._onMediaSourceEnded),n.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(n.addEventListener("startstreaming",this._onStartStreaming),n.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(n);if(this.appendSource)try{s.removeAttribute("src");const l=self.ManagedMediaSource;s.disableRemotePlayback=s.disableRemotePlayback||l&&n instanceof l,Er(s),Ec(s,o),s.load()}catch{s.src=o}else s.src=o;s.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:t,_objectUrl:s}=this;if(t){if(this.log("media source detaching"),t.readyState==="open")try{t.endOfStream()}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),t.removeEventListener("sourceopen",this._onMediaSourceOpen),t.removeEventListener("sourceended",this._onMediaSourceEnded),t.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.removeEventListener("startstreaming",this._onStartStreaming),t.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(e.removeAttribute("src"),this.appendSource&&Er(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(p.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const t=this.sourceBuffer[e];try{if(t){var s;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(s=this.mediaSource)!=null&&s.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}}catch(i){this.warn(`onBufferReset ${e}`,i)}}onBufferCodecs(e,t){const s=this.getSourceBufferTypes().length,i=Object.keys(t);if(i.forEach(n=>{if(s){const l=this.tracks[n];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:c,codec:h,levelCodec:u,container:d,metadata:g}=t[n],f=Ui(l.codec,l.levelCodec),m=f?.replace(pr,"$1");let E=Ui(h,u);const T=(o=E)==null?void 0:o.replace(pr,"$1");if(E&&m!==T){n.slice(0,5)==="audio"&&(E=os(E,this.appendSource));const y=`${d};codecs=${E}`;this.appendChangeType(n,y),this.log(`switching codec ${f} to ${E}`),this.tracks[n]={buffer:l.buffer,codec:h,container:d,levelCodec:u,metadata:g,id:c}}}}else this.pendingTracks[n]=t[n]}),s)return;const r=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==r&&(this.log(`${r} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=r),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,t){const{operationQueue:s}=this,i={execute:()=>{const r=this.sourceBuffer[e];r&&(this.log(`changing ${e} sourceBuffer type to ${t}`),r.changeType(t)),s.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:r=>{this.warn(`Failed to change ${e} SourceBuffer type`,r)}};s.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,t){const{hls:s,operationQueue:i,tracks:r}=this,{data:n,type:o,frag:l,part:c,chunkMeta:h}=t,u=h.buffering[o],d=self.performance.now();u.start=d;const g=l.stats.buffering,f=c?c.stats.buffering:null;g.start===0&&(g.start=d),f&&f.start===0&&(f.start=d);const m=r.audio;let E=!1;o==="audio"&&m?.container==="audio/mpeg"&&(E=!this.lastMpegAudioChunk||h.id===1||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);const T=l.start,y={execute:()=>{if(u.executeStart=self.performance.now(),E){const v=this.sourceBuffer[o];if(v){const A=T-v.timestampOffset;Math.abs(A)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${T} (delta: ${A}) sn: ${l.sn})`),v.timestampOffset=T)}}this.appendExecutor(n,o)},onStart:()=>{},onComplete:()=>{const v=self.performance.now();u.executeEnd=u.end=v,g.first===0&&(g.first=v),f&&f.first===0&&(f.first=v);const{sourceBuffer:A}=this,x={};for(const D in A)x[D]=ne.getBuffered(A[D]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(p.BUFFER_APPENDED,{type:o,frag:l,part:c,chunkMeta:h,parent:l.type,timeRanges:x})},onError:v=>{const A={type:W.MEDIA_ERROR,parent:l.type,details:b.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:c,chunkMeta:h,error:v,err:v,fatal:!1};if(v.code===DOMException.QUOTA_EXCEEDED_ERR)A.details=b.BUFFER_FULL_ERROR;else{const x=++this.appendErrors[o];A.details=b.BUFFER_APPEND_ERROR,this.warn(`Failed ${x}/${s.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),x>=s.config.appendErrorMaxRetry&&(A.fatal=!0)}s.trigger(p.ERROR,A)}};i.append(y,o,!!this.pendingTracks[o])}onBufferFlushing(e,t){const{operationQueue:s}=this,i=r=>({execute:this.removeExecutor.bind(this,r,t.startOffset,t.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(p.BUFFER_FLUSHED,{type:r})},onError:n=>{this.warn(`Failed to remove from ${r} SourceBuffer`,n)}});t.type?s.append(i(t.type),t.type):this.getSourceBufferTypes().forEach(r=>{s.append(i(r),r)})}onFragParsed(e,t){const{frag:s,part:i}=t,r=[],n=i?i.elementaryStreams:s.elementaryStreams;n[ie.AUDIOVIDEO]?r.push("audiovideo"):(n[ie.AUDIO]&&r.push("audio"),n[ie.VIDEO]&&r.push("video"));const o=()=>{const l=self.performance.now();s.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const c=i?i.stats:s.stats;this.hls.trigger(p.FRAG_BUFFERED,{frag:s,part:i,stats:c,id:s.type})};r.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${s.type} level: ${s.level} sn: ${s.sn}`),this.blockBuffers(o,r)}onFragChanged(e,t){this.trimBuffers()}onBufferEos(e,t){this.getSourceBufferTypes().reduce((i,r)=>{const n=this.sourceBuffer[r];return n&&(!t.type||t.type===r)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${r} sourceBuffer now EOS`))),i&&!!(!n||n.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(r=>{const n=this.sourceBuffer[r];n&&(n.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:t,media:s}=this;if(!s||t===null||!this.getSourceBufferTypes().length)return;const r=e.config,n=s.currentTime,o=t.levelTargetDuration,l=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(N(l)&&l>0){const c=Math.max(l,o),h=Math.floor(n/o)*o-c;this.flushBackBuffer(n,o,h)}if(N(r.frontBufferFlushThreshold)&&r.frontBufferFlushThreshold>0){const c=Math.max(r.maxBufferLength,r.frontBufferFlushThreshold),h=Math.max(c,o),u=Math.floor(n/o)*o+h;this.flushFrontBuffer(n,o,u)}}flushBackBuffer(e,t,s){const{details:i,sourceBuffer:r}=this;this.getSourceBufferTypes().forEach(o=>{const l=r[o];if(l){const c=ne.getBuffered(l);if(c.length>0&&s>c.start(0)){if(this.hls.trigger(p.BACK_BUFFER_REACHED,{bufferEnd:s}),i!=null&&i.live)this.hls.trigger(p.LIVE_BACK_BUFFER_REACHED,{bufferEnd:s});else if(l.ended&&c.end(c.length-1)-e<t*2){this.log(`Cannot flush ${o} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:0,endOffset:s,type:o})}}})}flushFrontBuffer(e,t,s){const{sourceBuffer:i}=this;this.getSourceBufferTypes().forEach(n=>{const o=i[n];if(o){const l=ne.getBuffered(o),c=l.length;if(c<2)return;const h=l.start(c-1),u=l.end(c-1);if(s>h||e>=h&&e<=u)return;if(o.ended&&e-u<2*t){this.log(`Cannot flush ${n} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(p.BUFFER_FLUSHING,{startOffset:h,endOffset:1/0,type:n})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:t,media:s,mediaSource:i}=this,r=e.fragments[0].start+e.totalduration,n=s.duration,o=N(i.duration)?i.duration:0;e.live&&t.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(r>o&&r>n||!N(n))&&(this.log(`Updating Media Source duration to ${r.toFixed(3)}`),i.duration=r)}updateSeekableRange(e){const t=this.mediaSource,s=e.fragments;if(s.length&&e.live&&t!=null&&t.setLiveSeekableRange){const r=Math.max(0,s[0].start),n=Math.max(r,r+e.totalduration);this.log(`Media Source duration is set to ${t.duration}. Setting seekable range to ${r}-${n}.`),t.setLiveSeekableRange(r,n)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:t,pendingTracks:s}=this,i=Object.keys(s).length;if(i&&(!e||i===2||"audiovideo"in s)){this.createSourceBuffers(s),this.pendingTracks={};const r=this.getSourceBufferTypes();if(r.length)this.hls.trigger(p.BUFFER_CREATED,{tracks:this.tracks}),r.forEach(n=>{t.executeNext(n)});else{const n=new Error("could not create source buffer for media codec(s)");this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:n,reason:n.message})}}}createSourceBuffers(e){const{sourceBuffer:t,mediaSource:s}=this;if(!s)throw Error("createSourceBuffers called when mediaSource was null");for(const r in e)if(!t[r]){var i;const n=e[r];if(!n)throw Error(`source buffer exists for track ${r}, however track does not`);let o=((i=n.levelCodec)==null?void 0:i.indexOf(","))===-1?n.levelCodec:n.codec;o&&r.slice(0,5)==="audio"&&(o=os(o,this.appendSource));const l=`${n.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const c=t[r]=s.addSourceBuffer(l),h=r;this.addBufferListener(h,"updatestart",this._onSBUpdateStart),this.addBufferListener(h,"updateend",this._onSBUpdateEnd),this.addBufferListener(h,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(h,"bufferedchange",(u,d)=>{const g=d.removedRanges;g!=null&&g.length&&this.hls.trigger(p.BUFFER_FLUSHED,{type:r})}),this.tracks[r]={buffer:c,codec:o,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(c){this.error(`error while trying to add sourceBuffer: ${c.message}`),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:c,sourceBufferName:r,mimeType:l})}}}get mediaSrc(){var e;const t=((e=this.media)==null?void 0:e.firstChild)||this.media;return t?.src}_onSBUpdateStart(e){const{operationQueue:t}=this;t.current(e).onStart()}_onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:s}=this;s.current(e).onComplete(),s.shiftAndExecuteNext(e)}_onSBUpdateError(e,t){var s;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(s=this.mediaSource)==null?void 0:s.readyState}`);this.error(`${i}`,t),this.hls.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const r=this.operationQueue.current(e);r&&r.onError(i)}removeExecutor(e,t,s){const{media:i,mediaSource:r,operationQueue:n,sourceBuffer:o}=this,l=o[e];if(!i||!r||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),n.shiftAndExecuteNext(e);return}const c=N(i.duration)?i.duration:1/0,h=N(r.duration)?r.duration:1/0,u=Math.max(0,t),d=Math.min(s,c,h);d>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${d}] from the ${e} SourceBuffer`),l.remove(u,d)):n.shiftAndExecuteNext(e)}appendExecutor(e,t){const s=this.sourceBuffer[t];if(!s){if(!this.pendingTracks[t])throw new Error(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);return}s.ended=!1,s.appendBuffer(e)}blockBuffers(e,t=this.getSourceBufferTypes()){if(!t.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:s}=this,i=t.map(r=>s.appendBlocker(r));Promise.all(i).then(()=>{e(),t.forEach(r=>{const n=this.sourceBuffer[r];n!=null&&n.updating||s.shiftAndExecuteNext(r)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,t,s){const i=this.sourceBuffer[e];if(!i)return;const r=s.bind(this,e);this.listeners[e].push({event:t,listener:r}),i.addEventListener(t,r)}removeBufferListeners(e){const t=this.sourceBuffer[e];t&&this.listeners[e].forEach(s=>{t.removeEventListener(s.event,s.listener)})}}function Er(a){const e=a.querySelectorAll("source");[].slice.call(e).forEach(t=>{a.removeChild(t)})}function Ec(a,e){const t=self.document.createElement("source");t.type="video/mp4",t.src=e,a.appendChild(t)}const Tc={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},Cn=a=>String.fromCharCode(Tc[a]||a),We=15,st=100,yc={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},vc={17:2,18:4,21:6,22:8,23:10,19:13,20:15},xc={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Sc={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Lc=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Ac{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const s=typeof t=="function"?t():t;S.log(`${this.time} [${e}] ${s}`)}}}const ct=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].toString(16));return t};class _n{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let s=0;s<t.length;s++){const i=t[s];e.hasOwnProperty(i)&&(this[i]=e[i])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}}class Rc{constructor(){this.uchar=" ",this.penState=new _n}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}}class bc{constructor(e){this.chars=[],this.pos=0,this.currPenState=new _n,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<st;t++)this.chars.push(new Rc);this.logger=e}equals(e){for(let t=0;t<st;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<st;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<st;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>st&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=st)}moveCursor(e){const t=this.pos+e;if(e>1)for(let s=this.pos+1;s<t+1;s++)this.chars[s].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=Cn(e);if(this.pos>=st){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<st;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let s=0;s<st;s++){const i=this.chars[s].uchar;i!==" "&&(t=!1),e.push(i)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}}class Os{constructor(e){this.rows=[],this.currRow=We-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<We;t++)this.rows.push(new bc(e));this.logger=e}reset(){for(let e=0;e<We;e++)this.rows[e].clear();this.currRow=We-1}equals(e){let t=!0;for(let s=0;s<We;s++)if(!this.rows[s].equals(e.rows[s])){t=!1;break}return t}copy(e){for(let t=0;t<We;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<We;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+JSON.stringify(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let o=0;o<We;o++)this.rows[o].clear();const r=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){const o=n.rows[r].cueStartTime,l=this.logger.time;if(o!==null&&l!==null&&o<l)for(let c=0;c<this.nrRollUpRows;c++)this.rows[t-this.nrRollUpRows+c+1].copy(n.rows[r+c])}}this.currRow=t;const s=this.rows[this.currRow];if(e.indent!==null){const r=e.indent,n=Math.max(r-1,0);s.setCursor(e.indent),e.color=s.chars[n].penState.foreground}const i={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(i)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+JSON.stringify(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let s="",i=-1;for(let r=0;r<We;r++){const n=this.rows[r].getTextString();n&&(i=r+1,e?t.push("Row "+i+": '"+n+"'"):t.push(n.trim()))}return t.length>0&&(e?s="["+t.join(" | ")+"]":s=t.join(`
15`)),s}getTextAndFormat(){return this.rows}}class Tr{constructor(e,t,s){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Os(s),this.nonDisplayedMemory=new Os(s),this.lastOutputScreen=new Os(s),this.currRollUpRow=this.displayedMemory.rows[We-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=s}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[We-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let s=0;s<e.length;s++)this.writeScreen.insertChar(e[s]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};if(t.underline=e%2===1,t.italics=e>=46,t.italics)t.foreground="white";else{const s=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];t.foreground=i[s]}this.logger.log(2,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}}class yr{constructor(e,t,s){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Dc(),this.logger=void 0;const i=this.logger=new Ac;this.channels=[null,new Tr(e,t,i),new Tr(e+1,s,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let s=0;s<t.length;s+=2){const i=t[s]&127,r=t[s+1]&127;let n=!1,o=null;if(i===0&&r===0)continue;this.logger.log(3,()=>"["+ct([t[s],t[s+1]])+"] -> ("+ct([i,r])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(Ic(i,r,l)){Vt(null,null,l),this.logger.log(3,()=>"Repeated command ("+ct([i,r])+") is dropped");continue}Vt(i,r,this.cmdHistory),n=this.parseCmd(i,r),n||(n=this.parseMidrow(i,r)),n||(n=this.parsePAC(i,r)),n||(n=this.parseBackgroundAttributes(i,r))}else Vt(null,null,l);if(!n&&(o=this.parseChars(i,r),o)){const h=this.currentChannel;h&&h>0?this.channels[h].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!n&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+ct([i,r])+" orig: "+ct([t[s],t[s+1]]))}}parseCmd(e,t){const s=(e===20||e===28||e===21||e===29)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=33&&t<=35;if(!(s||i))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let s=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?s=1:s=2,s!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[s];return i?(i.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+ct([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let s;const i=(e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127,r=(e===16||e===24)&&t>=64&&t<=95;if(!(i||r))return!1;const n=e<=23?1:2;t>=64&&t<=95?s=n===1?yc[e]:xc[e]:s=n===1?vc[e]:Sc[e];const o=this.channels[n];return o?(o.setPAC(this.interpretPAC(s,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let s;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?s=t-96:s=t-64,i.underline=(s&1)===1,s<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(s/2)]:s<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((s-16)/2)*4,i}parseChars(e,t){let s,i=null,r=null;if(e>=25?(s=2,r=e-8):(s=1,r=e),r>=17&&r<=19){let n;r===17?n=t+80:r===18?n=t+112:n=t+144,this.logger.log(2,()=>"Special char '"+Cn(n)+"' in channel "+s),i=[n]}else e>=32&&e<=127&&(i=t===0?[e]:[e,t]);return i&&this.logger.log(3,()=>"Char codes =  "+ct(i).join(",")),i}parseBackgroundAttributes(e,t){const s=(e===16||e===24)&&t>=32&&t<=47,i=(e===23||e===31)&&t>=45&&t<=47;if(!(s||i))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=Lc[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Vt(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const s=this.channels[t];s&&s.cueSplitAtTime(e)}}}function Vt(a,e,t){t.a=a,t.b=e}function Ic(a,e,t){return t.a===a&&t.b===e}function Dc(){return{a:null,b:null}}class Wt{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,s){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=s,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Li=(function(){if(At!=null&&At.VTTCue)return self.VTTCue;const a=["","lr","rl"],e=["start","middle","end","left","right"];function t(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const c=l.toLowerCase();return~o.indexOf(c)?c:!1}function s(o){return t(a,o)}function i(o){return t(e,o)}function r(o,...l){let c=1;for(;c<arguments.length;c++){const h=arguments[c];for(const u in h)o[u]=h[u]}return o}function n(o,l,c){const h=this,u={enumerable:!0};h.hasBeenReset=!1;let d="",g=!1,f=o,m=l,E=c,T=null,y="",v=!0,A="auto",x="start",D=50,R="middle",C=50,k="middle";Object.defineProperty(h,"id",r({},u,{get:function(){return d},set:function(I){d=""+I}})),Object.defineProperty(h,"pauseOnExit",r({},u,{get:function(){return g},set:function(I){g=!!I}})),Object.defineProperty(h,"startTime",r({},u,{get:function(){return f},set:function(I){if(typeof I!="number")throw new TypeError("Start time must be set to a number.");f=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",r({},u,{get:function(){return m},set:function(I){if(typeof I!="number")throw new TypeError("End time must be set to a number.");m=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",r({},u,{get:function(){return E},set:function(I){E=""+I,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",r({},u,{get:function(){return T},set:function(I){T=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",r({},u,{get:function(){return y},set:function(I){const w=s(I);if(w===!1)throw new SyntaxError("An invalid or illegal string was specified.");y=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",r({},u,{get:function(){return v},set:function(I){v=!!I,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",r({},u,{get:function(){return A},set:function(I){if(typeof I!="number"&&I!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");A=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",r({},u,{get:function(){return x},set:function(I){const w=i(I);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");x=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",r({},u,{get:function(){return D},set:function(I){if(I<0||I>100)throw new Error("Position must be between 0 and 100.");D=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",r({},u,{get:function(){return R},set:function(I){const w=i(I);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");R=w,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",r({},u,{get:function(){return C},set:function(I){if(I<0||I>100)throw new Error("Size must be between 0 and 100.");C=I,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",r({},u,{get:function(){return k},set:function(I){const w=i(I);if(!w)throw new SyntaxError("An invalid or illegal string was specified.");k=w,this.hasBeenReset=!0}})),h.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n})();class Cc{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function wn(a){function e(s,i,r,n){return(s|0)*3600+(i|0)*60+(r|0)+parseFloat(n||0)}const t=a.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return t?parseFloat(t[2])>59?e(t[2],t[3],0,t[4]):e(t[1],t[2],t[3],t[4]):null}class _c{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,s){return s?this.has(e)?this.values[e]:t[s]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,s){for(let i=0;i<s.length;++i)if(t===s[i]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const s=parseFloat(t);if(s>=0&&s<=100)return this.set(e,s),!0}return!1}}function kn(a,e,t,s){const i=s?a.split(s):[a];for(const r in i){if(typeof i[r]!="string")continue;const n=i[r].split(t);if(n.length!==2)continue;const o=n[0],l=n[1];e(o,l)}}const ti=new Li(0,0,""),Yt=ti.align==="middle"?"middle":"center";function wc(a,e,t){const s=a;function i(){const o=wn(a);if(o===null)throw new Error("Malformed timestamp: "+s);return a=a.replace(/^[^\sa-zA-Z-]+/,""),o}function r(o,l){const c=new _c;kn(o,function(d,g){let f;switch(d){case"region":for(let m=t.length-1;m>=0;m--)if(t[m].id===g){c.set(d,t[m].region);break}break;case"vertical":c.alt(d,g,["rl","lr"]);break;case"line":f=g.split(","),c.integer(d,f[0]),c.percent(d,f[0])&&c.set("snapToLines",!1),c.alt(d,f[0],["auto"]),f.length===2&&c.alt("lineAlign",f[1],["start",Yt,"end"]);break;case"position":f=g.split(","),c.percent(d,f[0]),f.length===2&&c.alt("positionAlign",f[1],["start",Yt,"end","line-left","line-right","auto"]);break;case"size":c.percent(d,g);break;case"align":c.alt(d,g,["start",Yt,"end","left","right"]);break}},/:/,/\s/),l.region=c.get("region",null),l.vertical=c.get("vertical","");let h=c.get("line","auto");h==="auto"&&ti.line===-1&&(h=-1),l.line=h,l.lineAlign=c.get("lineAlign","start"),l.snapToLines=c.get("snapToLines",!0),l.size=c.get("size",100),l.align=c.get("align",Yt);let u=c.get("position","auto");u==="auto"&&ti.position===50&&(u=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=u}function n(){a=a.replace(/^\s+/,"")}if(n(),e.startTime=i(),n(),a.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+s);a=a.slice(3),n(),e.endTime=i(),n(),r(a,e)}function Pn(a){return a.replace(/<br(?: \/)?>/gi,`
16`)}class kc{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Cc,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function s(){let r=t.buffer,n=0;for(r=Pn(r);n<r.length&&r[n]!=="\r"&&r[n]!==`
17`;)++n;const o=r.slice(0,n);return r[n]==="\r"&&++n,r[n]===`
18`&&++n,t.buffer=r.slice(n),o}function i(r){kn(r,function(n,o){},/:/)}try{let r="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;r=s();const o=r.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let n=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(n?n=!1:r=s(),t.state){case"HEADER":/:/.test(r)?i(r):r||(t.state="ID");continue;case"NOTE":r||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(r)){t.state="NOTE";break}if(!r)continue;if(t.cue=new Li(0,0,""),t.state="CUE",r.indexOf("-->")===-1){t.cue.id=r;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{wc(r,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const o=r.indexOf("-->")!==-1;if(!r||o&&(n=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
19`),t.cue.text+=r}continue;case"BADCUE":r||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
20
21`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}}const Pc=/\r\n|\n\r|\n|\r/g,Ms=function(e,t,s=0){return e.slice(s,s+t.length)===t},Fc=function(e){let t=parseInt(e.slice(-3));const s=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),r=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!N(t)||!N(s)||!N(i)||!N(r))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*s,t+=60*1e3*i,t+=3600*1e3*r,t},Ns=function(e){let t=5381,s=e.length;for(;s;)t=t*33^e.charCodeAt(--s);return(t>>>0).toString()};function Ai(a,e,t){return Ns(a.toString())+Ns(e.toString())+Ns(t)}const Oc=function(e,t,s){let i=e[t],r=e[i.prevCC];if(!r||!r.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(n=r)!=null&&n.new;){var n;e.ccOffset+=i.start-r.start,i.new=!1,i=r,r=e[i.prevCC]}e.presentationOffset=s};function Mc(a,e,t,s,i,r,n){const o=new kc,l=Je(new Uint8Array(a)).trim().replace(Pc,`
22`).split(`
23`),c=[],h=e?Zl(e.baseTime,e.timescale):0;let u="00:00.000",d=0,g=0,f,m=!0;o.oncue=function(E){const T=t[s];let y=t.ccOffset;const v=(d-h)/9e4;if(T!=null&&T.new&&(g!==void 0?y=t.ccOffset=T.start:Oc(t,s,v)),v){if(!e){f=new Error("Missing initPTS for VTT MPEGTS");return}y=v-t.presentationOffset}const A=E.endTime-E.startTime,x=Ge((E.startTime+y-g)*9e4,i*9e4)/9e4;E.startTime=Math.max(x,0),E.endTime=Math.max(x+A,0);const D=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(D)),E.id||(E.id=Ai(E.startTime,E.endTime,D)),E.endTime>0&&c.push(E)},o.onparsingerror=function(E){f=E},o.onflush=function(){if(f){n(f);return}r(c)},l.forEach(E=>{if(m)if(Ms(E,"X-TIMESTAMP-MAP=")){m=!1,E.slice(16).split(",").forEach(T=>{Ms(T,"LOCAL:")?u=T.slice(6):Ms(T,"MPEGTS:")&&(d=parseInt(T.slice(7)))});try{g=Fc(u)/1e3}catch(T){f=T}return}else E===""&&(m=!1);o.parse(E+`
24`)}),o.flush()}const Us="stpp.ttml.im1t",Fn=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,On=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Nc={left:"start",center:"center",right:"end",start:"start",end:"end"};function vr(a,e,t,s){const i=Q(new Uint8Array(a),["mdat"]);if(i.length===0){s(new Error("Could not parse IMSC1 mdat"));return}const r=i.map(o=>Je(o)),n=Jl(e.baseTime,1,e.timescale);try{r.forEach(o=>t(Uc(o,n)))}catch(o){s(o)}}function Uc(a,e){const i=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(r).reduce((u,d)=>(u[d]=i.getAttribute(`ttp:${d}`)||r[d],u),{}),o=i.getAttribute("xml:space")!=="preserve",l=xr(Bs(i,"styling","style")),c=xr(Bs(i,"layout","region")),h=Bs(i,"body","[begin]");return[].map.call(h,u=>{const d=Mn(u,o);if(!d||!u.hasAttribute("begin"))return null;const g=$s(u.getAttribute("begin"),n),f=$s(u.getAttribute("dur"),n);let m=$s(u.getAttribute("end"),n);if(g===null)throw Sr(u);if(m===null){if(f===null)throw Sr(u);m=g+f}const E=new Li(g-e,m-e,d);E.id=Ai(E.startTime,E.endTime,E.text);const T=c[u.getAttribute("region")],y=l[u.getAttribute("style")],v=Bc(T,y,l),{textAlign:A}=v;if(A){const x=Nc[A];x&&(E.lineAlign=x),E.align=A}return me(E,v),E}).filter(u=>u!==null)}function Bs(a,e,t){const s=a.getElementsByTagName(e)[0];return s?[].slice.call(s.querySelectorAll(t)):[]}function xr(a){return a.reduce((e,t)=>{const s=t.getAttribute("xml:id");return s&&(e[s]=t),e},{})}function Mn(a,e){return[].slice.call(a.childNodes).reduce((t,s,i)=>{var r;return s.nodeName==="br"&&i?t+`
25`:(r=s.childNodes)!=null&&r.length?Mn(s,e):e?t+s.textContent.trim().replace(/\s+/g," "):t+s.textContent},"")}function Bc(a,e,t){const s="http://www.w3.org/ns/ttml#styling";let i=null;const r=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],n=a!=null&&a.hasAttribute("style")?a.getAttribute("style"):null;return n&&t.hasOwnProperty(n)&&(i=t[n]),r.reduce((o,l)=>{const c=Gs(e,s,l)||Gs(a,s,l)||Gs(i,s,l);return c&&(o[l]=c),o},{})}function Gs(a,e,t){return a&&a.hasAttributeNS(e,t)?a.getAttributeNS(e,t):null}function Sr(a){return new Error(`Could not parse ttml timestamp ${a}`)}function $s(a,e){if(!a)return null;let t=wn(a);return t===null&&(Fn.test(a)?t=Gc(a,e):On.test(a)&&(t=$c(a,e))),t}function Gc(a,e){const t=Fn.exec(a),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 $c(a,e){const t=On.exec(a),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 Kc{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=Ar(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(p.FRAG_LOADING,this.onFragLoading,this),e.on(p.FRAG_LOADED,this.onFragLoaded,this),e.on(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(p.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(p.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(p.FRAG_LOADING,this.onFragLoading,this),e.off(p.FRAG_LOADED,this.onFragLoaded,this),e.off(p.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(p.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(p.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(p.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(p.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new Wt(this,"textTrack1"),t=new Wt(this,"textTrack2"),s=new Wt(this,"textTrack3"),i=new Wt(this,"textTrack4");this.cea608Parser1=new yr(1,e,t),this.cea608Parser2=new yr(3,s,i)}}addCues(e,t,s,i,r){let n=!1;for(let o=r.length;o--;){const l=r[o],c=Hc(l[0],l[1],t,s);if(c>=0&&(l[0]=Math.min(l[0],t),l[1]=Math.max(l[1],s),n=!0,c/(s-t)>.5))return}if(n||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:n}=this;s==="main"&&(this.initPTS[t.cc]={baseTime:i,timescale:r}),n.length&&(this.unparsedVttFrags=[],n.forEach(o=>{this.onFragLoaded(p.FRAG_LOADED,o)}))}getExistingTrack(e,t){const{media:s}=this;if(s)for(let i=0;i<s.textTracks.length;i++){const r=s.textTracks[i];if(Lr(r,{name:e,lang:t}))return r}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:s,media:i}=this,{label:r,languageCode:n}=t[e],o=this.getExistingTrack(r,n);if(o)s[e]=o,vt(s[e]),tn(s[e],i);else{const l=this.createTextTrack("captions",r,n);l&&(l[e]=!0,s[e]=l)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const s=t.label,i={_id:e,label:s,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=i,this.hls.trigger(p.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[i]})}createTextTrack(e,t,s){const i=this.media;if(i)return i.addTextTrack(e,t,s)}onMediaAttaching(e,t){this.media=t.media,this._cleanTracks()}onMediaDetaching(){const{captionsTracks:e}=this;Object.keys(e).forEach(t=>{vt(e[t]),delete e[t]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=Ar(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let s=0;s<t.length;s++)vt(t[s])}onSubtitleTracksUpdated(e,t){const s=t.subtitleTracks||[],i=s.some(r=>r.textCodec===Us);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(Dn(this.tracks,s)){this.tracks=s;return}if(this.textTracks=[],this.tracks=s,this.config.renderTextTracksNatively){const n=this.media,o=n?Xt(n.textTracks):null;if(this.tracks.forEach((l,c)=>{let h;if(o){let u=null;for(let d=0;d<o.length;d++)if(o[d]&&Lr(o[d],l)){u=o[d],o[d]=null;break}u&&(h=u)}if(h)vt(h);else{const u=Nn(l);h=this.createTextTrack(u,l.name,l.lang),h&&(h.mode="disabled")}h&&this.textTracks.push(h)}),o!=null&&o.length){const l=o.filter(c=>c!==null).map(c=>c.label);l.length&&S.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 n=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:n})}}}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]}`,n=this.captionsProperties[r];n&&(n.label=s.name,s.lang&&(n.languageCode=s.lang),n.media=s)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===H.MAIN){var s,i;const{cea608Parser1:r,cea608Parser2:n,lastSn:o}=this,{cc:l,sn:c}=t.frag,h=(s=(i=t.part)==null?void 0:i.index)!=null?s:-1;r&&n&&(c!==o+1||c===o&&h!==this.lastPartIndex+1||l!==this.lastCc)&&(r.reset(),n.reset()),this.lastCc=l,this.lastSn=c,this.lastPartIndex=h}}onFragLoaded(e,t){const{frag:s,payload:i}=t;if(s.type===H.SUBTITLE)if(i.byteLength){const r=s.decryptdata,n="stats"in t;if(r==null||!r.encrypted||n){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===Us?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;vr(t,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),s.trigger(p.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{S.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:n}=this,o=r.length-1;if(!r[s.cc]&&o===-1){n.push(e);return}const l=this.hls,c=(t=s.initSegment)!=null&&t.data?He(s.initSegment.data,new Uint8Array(i)):i;Mc(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?n.push(e):this._fallbackToIMSC1(s,i),S.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||vr(t,this.initPTS[e.cc],()=>{s.textCodec=Us,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=>sn(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===H.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:n}=t;if(!(r.type===H.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let o=0;o<n.length;o++){const l=n[o].bytes;if(l){const c=this.extractCea608Data(l);s.addData(n[o].pts,c[0]),i.addData(n[o].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:s,endOffsetSubtitles:i,type:r}){const{media:n}=this;if(!(!n||n.currentTime<s)){if(!r||r==="video"){const{captionsTracks:o}=this;Object.keys(o).forEach(l=>zs(o[l],t,s))}if(this.config.renderTextTracksNatively&&t===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>zs(o[l],t,i))}}}extractCea608Data(e){const t=[[],[]],s=e[0]&31;let i=2;for(let r=0;r<s;r++){const n=e[i++],o=127&e[i++],l=127&e[i++];if(o===0&&l===0)continue;if((4&n)!==0){const h=3&n;(h===0||h===1)&&(t[h].push(o),t[h].push(l))}}return t}}function Nn(a){return a.characteristics&&/transcribes-spoken-dialog/gi.test(a.characteristics)&&/describes-music-and-sound/gi.test(a.characteristics)?"captions":"subtitles"}function Lr(a,e){return!!a&&a.kind===Nn(e)&&ei(e,a)}function Hc(a,e,t,s){return Math.min(e,s)-Math.max(a,t)}function Ar(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}class Ri{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:e}=this;e.on(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.BUFFER_CODECS,this.onBufferCodecs,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:e}=this;e.off(p.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(p.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.BUFFER_CODECS,this.onBufferCodecs,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){const s=this.hls.levels[t.droppedLevel];this.isLevelAllowed(s)&&this.restrictedLevels.push({bitrate:s.bitrate,height:s.height,width:s.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){const s=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,s.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&N(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping()}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const e=this.hls.levels;if(e.length){const t=this.hls,s=this.getMaxLevel(e.length-1);s!==this.autoLevelCapping&&S.log(`Setting autoLevelCapping to ${s}: ${e[s].height}p@${e[s].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=s,t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(e){const t=this.hls.levels;if(!t.length)return-1;const s=t.filter((i,r)=>this.isLevelAllowed(i)&&r<=e);return this.clientRect=null,Ri.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 n=Math.max(t,s);for(let o=0;o<e.length;o+=1){const l=e[o];if((l.width>=n||l.height>=n)&&i(l,e[o+1])){r=o;break}}return r}}class Vc{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,n=s-this.lastDroppedFrames,o=t-this.lastDecodedFrames,l=1e3*n/r,c=this.hls;if(c.trigger(p.FPS_DROP,{currentDropped:n,currentDecoded:o,totalDroppedFrames:s}),l>0&&n>c.config.fpsDroppedMonitoringThreshold*o){let h=c.currentLevel;S.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 jt="[eme]";class Lt{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=Lt.CDMCleanupPromise?[Lt.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=S.debug.bind(S,jt),this.log=S.log.bind(S,jt),this.warn=S.warn.bind(S,jt),this.error=S.error.bind(S,jt),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===le.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=(n,o,l)=>!!n&&l.indexOf(n)===o,i=t.map(n=>n.audioCodec).filter(s),r=t.map(n=>n.videoCodec).filter(s);return i.length+r.length===0&&r.push("avc1.42e01e"),new Promise((n,o)=>{const l=c=>{const h=c.shift();this.getMediaKeysPromise(h,i,r).then(u=>n({keySystem:h,mediaKeys:u})).catch(u=>{c.length?l(c):u instanceof Be?o(u):o(new Be({type:W.KEY_SYSTEM_ERROR,details:b.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 Kr===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=Xa(e,t,s,this.config.drmSystemOptions),r=this.keySystemAccessPromises[e];let n=r?.keySystemAccess;if(!n){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),n=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:n};return n.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),n.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 n.then(()=>r.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:s}){this.log(`Creating key-system session "${t}" keyId: ${ze.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 ze.hexDump(e.keyId)}updateKeySession(e,t){var s;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${ze.hexDump(((s=e.decryptdata)==null?void 0:s.keyId)||[])}
26      } (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=Ls(this.config),r=e.map(wi).filter(n=>!!n&&i.indexOf(n)!==-1);return this.getKeySystemSelectionPromise(r).then(({keySystem:n})=>{const o=ki(n);o?t(o):s(new Error(`Unable to find format for key-system "${n}"`))}).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:n,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(n,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:n,mediaKeys:o,decryptdata:t});return this.generateRequestWithPreferredKeySession(l,"cenc",t.pssh,"playlist-key")}))),r.catch(n=>this.handleError(n))),r}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof Be?this.hls.trigger(p.ERROR,e.data):this.hls.trigger(p.ERROR,{type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const t=this.getKeyIdString(e),s=this.keyIdToKeySessionPromise[t];if(!s){const i=wi(e.keyFormat),r=i?[i]:Ls(this.config);return this.attemptKeySystemAccess(r)}return s}getKeySystemSelectionPromise(e){if(e.length||(e=Ls(this.config)),e.length===0)throw new Be({type:W.KEY_SYSTEM_ERROR,details:b.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[le.FAIRPLAY]){const h=pe(new Uint8Array(s));try{const u=hi(JSON.parse(h).sinf),d=Xr(new Uint8Array(u));if(!d)return;i=d.subarray(8,24),r=le.FAIRPLAY}catch{this.warn('Failed to parse sinf "encrypted" event message initData');return}}else{const h=So(s);if(h===null)return;h.version===0&&h.systemId===$r.WIDEVINE&&h.data&&(i=h.data.subarray(8,24)),r=qa(h.systemId)}if(!r||!i)return;const n=ze.hexDump(i),{keyIdToKeySessionPromise:o,mediaKeySessions:l}=this;let c=o[n];for(let h=0;h<l.length;h++){const u=l[h],d=u.decryptdata;if(d.pssh||!d.keyId)continue;const g=ze.hexDump(d.keyId);if(n===g||d.uri.replace(/-/g,"").indexOf(n)!==-1){c=o[g],delete o[g],d.pssh=new Uint8Array(s),d.keyId=i,c=o[n]=c.then(()=>this.generateRequestWithPreferredKeySession(u,t,s,"encrypted-event-key-match"));break}}c||(c=o[n]=this.getKeySystemSelectionPromise([r]).then(({keySystem:h,mediaKeys:u})=>{var d;this.throwIfDestroyed();const g=new Pt("ISO-23001-7",n,(d=ki(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,n;const o=(r=this.config.drmSystems)==null||(n=r[e.keySystem])==null?void 0:n.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 Si,u=e._onmessage=f=>{const m=e.mediaKeysSession;if(!m){h.emit("error",new Error("invalid state"));return}const{messageType:E,message:T}=f;this.log(`"${E}" message event for session "${m.sessionId}" message size: ${T.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(e,T).catch(y=>{this.handleError(y),h.emit("error",y)}):E==="license-release"?e.keySystem===le.FAIRPLAY&&(this.updateKeySession(e,Ys("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${E}"`)},d=e._onkeystatuseschange=f=>{if(!e.mediaKeysSession){h.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const E=e.keyStatus;h.emit("keyStatus",E),E==="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",E=>{E.startsWith("usable")?f():E==="output-restricted"?m(new Be({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):E==="internal-error"?m(new Be({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${E}"`)):E==="expired"?m(new Error("key expired while generating request")):this.warn(`unhandled key status change "${E}"`)})});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 Be({type:W.KEY_SYSTEM_ERROR,details:b.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: ${ze.hexDump("buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s))} session keyId: ${ze.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((n,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)=>{n(d.data)},onError:(d,g,f,m)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:f,response:Le({url:l.url,data:void 0},d)},`"${e}" certificate request failed (${r}). Status: ${d.code} (${d.text})`))},onTimeout:(d,g,f)=>{o(new Be({type:W.KEY_SYSTEM_ERROR,details:b.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(n=>{this.log(`setServerCertificate ${n?"success":"not supported by CDM"} (${s?.byteLength}) on "${t}"`),i(e)}).catch(n=>{r(new Be({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:n,fatal:!0},n.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(s=>this.updateKeySession(e,new Uint8Array(s)).catch(i=>{throw new Be({type:W.KEY_SYSTEM_ERROR,details:b.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<d;u++){var n,o;h=r[u];const g=(n=h.querySelector("name"))==null?void 0:n.textContent,f=(o=h.querySelector("value"))==null?void 0:o.textContent;g&&f&&e.setRequestHeader(g,f)}}const l=i.querySelector("Challenge"),c=l?.textContent;if(!c)throw new Error("Cannot find <Challenge> in key message");return Ys(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(n=>{if(!s.decryptdata)throw n;return e.open("POST",t,!0),r.call(this.hls,e,t,s,i)}).then(n=>(e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:n||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 n=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${n}`);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,n,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 Be({type:W.KEY_SYSTEM_ERROR,details:b.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:n,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${n}). 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,n,e,t).then(({xhr:l,licenseChallenge:c})=>{e.keySystem==le.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={},Pt.clearKeyUriToKeyIdMap();const s=t.length;Lt.CDMCleanupPromise=Promise.all(t.map(i=>this.removeSession(i)).concat(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}`)})}}}Lt.CDMCleanupPromise=void 0;class Be 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 Ie;(function(a){a.MANIFEST="m",a.AUDIO="a",a.VIDEO="v",a.MUXED="av",a.INIT="i",a.CAPTION="c",a.TIMED_TEXT="tt",a.KEY="k",a.OTHER="o"})(Ie||(Ie={}));var si;(function(a){a.DASH="d",a.HLS="h",a.SMOOTH="s",a.OTHER="o"})(si||(si={}));var dt;(function(a){a.OBJECT="CMCD-Object",a.REQUEST="CMCD-Request",a.SESSION="CMCD-Session",a.STATUS="CMCD-Status"})(dt||(dt={}));const Wc={[dt.OBJECT]:["br","d","ot","tb"],[dt.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[dt.SESSION]:["cid","pr","sf","sid","st","v"],[dt.STATUS]:["bs","rtp"]};class It{constructor(e,t){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(s=>s instanceof It?s:new It(s))),this.value=e,this.params=t}}class Un{constructor(e){this.description=void 0,this.description=e}}const Yc="Dict";function jc(a){return Array.isArray(a)?JSON.stringify(a):a instanceof Map?"Map{}":a instanceof Set?"Set{}":typeof a=="object"?JSON.stringify(a):String(a)}function zc(a,e,t,s){return new Error(`failed to ${a} "${jc(e)}" as ${t}`,{cause:s})}const Rr="Bare Item",qc="Boolean",Xc="Byte Sequence",Qc="Decimal",Jc="Integer";function Zc(a){return a<-999999999999999||999999999999999<a}const eh=/[\x00-\x1f\x7f]+/,th="Token",sh="Key";function Ze(a,e,t){return zc("serialize",a,e,t)}function ih(a){if(typeof a!="boolean")throw Ze(a,qc);return a?"?1":"?0"}function rh(a){return btoa(String.fromCharCode(...a))}function nh(a){if(ArrayBuffer.isView(a)===!1)throw Ze(a,Xc);return`:${rh(a)}:`}function Bn(a){if(Zc(a))throw Ze(a,Jc);return a.toString()}function ah(a){return`@${Bn(a.getTime()/1e3)}`}function Gn(a,e){if(a<0)return-Gn(-a,e);const t=Math.pow(10,e);if(Math.abs(a*t%1-.5)<Number.EPSILON){const i=Math.floor(a*t);return(i%2===0?i:i+1)/t}else return Math.round(a*t)/t}function oh(a){const e=Gn(a,3);if(Math.floor(Math.abs(e)).toString().length>12)throw Ze(a,Qc);const t=e.toString();return t.includes(".")?t:`${t}.0`}const lh="String";function ch(a){if(eh.test(a))throw Ze(a,lh);return`"${a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function hh(a){return a.description||a.toString().slice(7,-1)}function br(a){const e=hh(a);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Ze(e,th);return e}function ii(a){switch(typeof a){case"number":if(!N(a))throw Ze(a,Rr);return Number.isInteger(a)?Bn(a):oh(a);case"string":return ch(a);case"symbol":return br(a);case"boolean":return ih(a);case"object":if(a instanceof Date)return ah(a);if(a instanceof Uint8Array)return nh(a);if(a instanceof Un)return br(a);default:throw Ze(a,Rr)}}function ri(a){if(/^[a-z*][a-z0-9\-_.*]*$/.test(a)===!1)throw Ze(a,sh);return a}function bi(a){return a==null?"":Object.entries(a).map(([e,t])=>t===!0?`;${ri(e)}`:`;${ri(e)}=${ii(t)}`).join("")}function $n(a){return a instanceof It?`${ii(a.value)}${bi(a.params)}`:ii(a)}function uh(a){return`(${a.value.map($n).join(" ")})${bi(a.params)}`}function dh(a,e={whitespace:!0}){if(typeof a!="object")throw Ze(a,Yc);const t=a instanceof Map?a.entries():Object.entries(a),s=e!=null&&e.whitespace?" ":"";return Array.from(t).map(([i,r])=>{r instanceof It||(r=new It(r));let n=ri(i);return r.value===!0?n+=bi(r.params):(n+="=",Array.isArray(r.value)?n+=uh(r):n+=$n(r)),n}).join(`,${s}`)}function fh(a,e){return dh(a,e)}const gh=a=>a==="ot"||a==="sf"||a==="st",mh=a=>typeof a=="number"?N(a):a!=null&&a!==""&&a!==!1;function ph(a,e){const t=new URL(a),s=new URL(e);if(t.origin!==s.origin)return a;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 Eh(){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 ss=a=>Math.round(a),Th=(a,e)=>(e!=null&&e.baseUrl&&(a=ph(a,e.baseUrl)),encodeURIComponent(a)),zt=a=>
26ss(a/100)*100,yh={br:ss,d:ss,bl:zt,dl:zt,mtp:zt,nor:Th,rtp:zt,tb:ss};function vh(a,e){const t={};if(a==null||typeof a!="object")return t;const s=Object.keys(a).sort(),i=me({},yh,e?.formatters),r=e?.filter;return s.forEach(n=>{if(r!=null&&r(n))return;let o=a[n];const l=i[n];l&&(o=l(o,e)),!(n==="v"&&o===1)&&(n=="pr"&&o===1||mh(o)&&(gh(n)&&typeof o=="string"&&(o=new Un(o)),t[n]=o))}),t}function Kn(a,e={}){return a?fh(vh(a,e),me({whitespace:!1},e)):""}function xh(a,e={}){if(!a)return{};const t=Object.entries(a),s=Object.entries(Wc).concat(Object.entries(e?.customHeaderMap||{})),i=t.reduce((r,n)=>{var o,l;const[c,h]=n,u=((o=s.find(d=>d[1].includes(c)))==null?void 0:o[0])||dt.REQUEST;return(l=r[u])!=null||(r[u]={}),r[u][c]=h,r},{});return Object.entries(i).reduce((r,[n,o])=>(r[n]=Kn(o,e),r),{})}function Sh(a,e,t){return me(a,xh(e,t))}const Lh="CMCD";function Ah(a,e={}){if(!a)return"";const t=Kn(a,e);return`${Lh}=${encodeURIComponent(t)}`}const Ir=/CMCD=[^&#]+/;function Rh(a,e,t){const s=Ah(e,t);if(!s)return a;if(Ir.test(a))return a.replace(Ir,s);const i=a.includes("?")?"&":"?";return`${a}${i}${s}`}class bh{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:Ie.MANIFEST,su:!this.initialized})}catch(r){S.warn("Could not generate manifest CMCD data.",r)}},this.applyFragmentData=i=>{try{const r=i.frag,n=this.hls.levels[r.level],o=this.getObjectType(r),l={d:r.duration*1e3,ot:o};(o===Ie.VIDEO||o===Ie.AUDIO||o==Ie.MUXED)&&(l.br=n.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(r){S.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||Eh(),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:si.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){me(t,this.createData());const s=t.ot===Ie.INIT||t.ot===Ie.VIDEO||t.ot===Ie.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,n)=>(i.includes(n)&&(r[n]=t[n]),r),{})),this.useHeaders?(e.headers||(e.headers={}),Sh(e.headers,t)):e.url=Rh(e.url,t)}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Ie.TIMED_TEXT;if(e.sn==="initSegment")return Ie.INIT;if(t==="audio")return Ie.AUDIO;if(t==="main")return this.hls.audioTracks.length?Ie.VIDEO:Ie.MUXED}getTopBandwidth(e){let t=0,s;const i=this.hls;if(e===Ie.AUDIO)s=i.audioTracks;else{const r=i.maxAutoLevel,n=r>-1?r+1:i.levels.length;s=i.levels.slice(0,n)}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===Ie.AUDIO?this.audioBuffer:this.videoBuffer;return!s||!t?NaN:ne.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,n,o){t(r),this.loader.load(r,n,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,n,o){t(r),this.loader.load(r,n,o)}}}}const Ih=3e5;class Dh{constructor(e){this.hls=void 0,this.log=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this.pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.log=S.log.bind(S,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(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))}
vendor: 6,328 bytes, line 26
26startLoad(){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?.action===Ae.SendAlternateToPenaltyBox&&s.flags===Ve.MoveAllAlternatesMatchingHost){const i=this.levels;let r=this.pathwayPriority,n=this.pathwayId;if(t.context){const{groupId:o,pathwayId:l,type:c}=t.context;o&&i?n=this.getPathwayForGroupId(o,c,n):l&&(n=l)}n in this.penalizedPathways||(this.penalizedPathways[n]=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!==n),s.resolved||S.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${n} 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]>Ih&&delete s[r]});for(let r=0;r<e.length;r++){const n=e[r];if(n in s)continue;if(n===this.pathwayId)return;const o=this.hls.nextLoadLevel,l=this.hls.levels[o];if(t=this.getLevelsForPathway(n),t.length>0){this.log(`Setting Pathway to "${n}"`),this.pathwayId=n,on(t),this.hls.trigger(p.LEVELS_UPDATED,{levels:t});const c=this.hls.levels[o];l&&c&&this.levels&&(c.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&c.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${c.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,t,s){const i=this.getLevelsForPathway(s).concat(this.levels||[]);for(let r=0;r<i.length;r++)if(t===te.AUDIO_TRACK&&i[r].hasAudioGroup(e)||t===te.SUBTITLE_TRACK&&i[r].hasSubtitleGroup(e))return i[r].pathwayId;return s}clonePathways(e){const t=this.levels;if(!t)return;const s={},i={};e.forEach(r=>{const{ID:n,"BASE-ID":o,"URI-REPLACEMENT":l}=r;if(t.some(h=>h.pathwayId===n))return;const c=this.getLevelsForPathway(o).map(h=>{const u=new ce(h.attrs);u["PATHWAY-ID"]=n;const d=u.AUDIO&&`${u.AUDIO}_clone_${n}`,g=u.SUBTITLES&&`${u.SUBTITLES}_clone_${n}`;d&&(s[u.AUDIO]=d,u.AUDIO=d),g&&(i[u.SUBTITLES]=g,u.SUBTITLES=g);const f=Hn(h.uri,u["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),m=new Rt({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 E=1;E<h.audioGroups.length;E++)m.addGroupId("audio",`${h.audioGroups[E]}_clone_${n}`);if(h.subtitleGroups)for(let E=1;E<h.subtitleGroups.length;E++)m.addGroupId("text",`${h.subtitleGroups[E]}_clone_${n}`);return m});t.push(...c),Dr(this.audioTracks,s,l,n),Dr(this.subtitleTracks,i,l,n)})}loadSteeringManifest(e){const t=this.hls.config,s=t.loader;this.loader&&this.loader.destroy(),this.loader=new s(t);let i;try{i=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(i.protocol!=="data:"){const h=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;i.searchParams.set("_HLS_pathway",this.pathwayId),i.searchParams.set("_HLS_throughput",""+h)}const r={responseType:"json",url:i.href},n=t.steeringManifestLoadPolicy.default,o=n.errorRetry||n.timeoutRetry||{},l={loadPolicy:n,timeout:n.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0},c={onSuccess:(h,u,d,g)=>{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":E,"PATHWAY-PRIORITY":T}=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),E&&this.clonePathways(E);const y={steeringManifest:f,url:i.toString()};this.hls.trigger(p.STEERING_MANIFEST_LOADED,y),T&&this.updatePathwayPriority(T)},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?.getResponseHeader=="function"){const E=m.getResponseHeader("Retry-After");E&&(f=parseFloat(E)*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 Dr(a,e,t,s){a&&Object.keys(e).forEach(i=>
26{const r=a.filter(n=>n.groupId===i).map(n=>{const o=me({},n);return o.details=void 0,o.attrs=new ce(o.attrs),o.url=o.attrs.URI=Hn(n.url,n.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",t),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=s,o});a.push(...r)})}function Hn(a,e,t,s){const{HOST:i,PARAMS:r,[t]:n}=s;let o;e&&(o=n?.[e],o&&(a=o));const l=new self.URL(a);return i&&!o&&(l.host=i),r&&Object.keys(r).sort().forEach(c=>{c&&l.searchParams.set(c,r[c])}),l.href}const Ch=/^age:\s*[\d.]+\s*$/im;class Vn{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 Es,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,s){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=s,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const s=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const r=this.xhrSetup;r?Promise.resolve().then(()=>{if(!(this.loader!==s||this.stats.aborted))return r(s,t.url)}).catch(n=>{if(!(this.loader!==s||this.stats.aborted))return s.open("GET",t.url,!0),r(s,t.url)}).then(()=>{this.loader!==s||this.stats.aborted||this.openAndSendXhr(s,t,e)}).catch(n=>{this.callbacks.onError({code:s.status,text:n.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:n}=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&&N(r)?r:n,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 n=t.status,o=t.responseType!=="text";if(n>=200&&n<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:n};this.callbacks.onSuccess(u,s,e,t)}else{const l=r.loadPolicy.errorRetry,c=s.retry,h={url:e.url,data:void 0,code:n};hs(l,c,!1,h)?this.retry(l):(S.error(`${n} while loading ${e.url}`),this.callbacks.onError({code:n,text:t.statusText},e,t,s))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(hs(e,t,!0))this.retry(e);else{var s;S.warn(`timeout while loading ${(s=this.context)==null?void 0:s.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:s}=this;this.retryDelay=fi(e,s.retry),s.retry++,S.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${s.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&Ch.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 _h(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const wh=/(\d+)-(\d+)\/(\d+)/;class Cr{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||Oh,this.controller=new self.AbortController,this.stats=new Es}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=kh(e,this.controller.signal),n=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&&N(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 Mh(f||"fetch, bad network response",g,u)}return i.loading.first=d,i.total=Fh(u.headers)||i.total,n&&N(t.highWaterMark)?this.loadProgressively(u,i,e,t.highWaterMark,n):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};n&&!N(t.highWaterMark)&&n(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 n=new un,o=e.body.getReader(),l=()=>o.read().then(c=>{if(c.done)return n.dataLength&&r(t,s,n.flush(),e),Promise.resolve(new ArrayBuffer(0));const h=c.value,u=h.length;return t.loaded+=u,u<i||n.dataLength?(n.push(h),n.dataLength>=i&&r(t,s,n.flush(),e)):r(t,s,h,e),l()}).catch(()=>Promise.reject());return l()}}function kh(a,e){const t={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(me({},a.headers))};return a.rangeEnd&&t.headers.set("Range","bytes="+a.rangeStart+"-"+String(a.rangeEnd-1)),t}function Ph(a){const e=wh.exec(a);if(e)return parseInt(e[2])-parseInt(e[1])+1}function Fh(a){const e=a.get("Content-Range");if(e){const s=Ph(e);if(N(s))return s}const t=a.get("Content-Length");if(t)return parseInt(t)}
vendor: 5,348 bytes, line 26
26function Oh(a,e){return new self.Request(a.url,e)}class Mh extends Error{constructor(e,t,s){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=s}}const Nh=/\s/,Uh={newCue(a,e,t,s){const i=[];let r,n,o,l,c;const h=self.VTTCue||self.TextTrackCue;for(let d=0;d<s.rows.length;d++)if(r=s.rows[d],o=!0,l=0,c="",!r.isEmpty()){var u;for(let m=0;m<r.chars.length;m++)Nh.test(r.chars[m].uchar)&&o?l++:(c+=r.chars[m].uchar,o=!1);r.cueStartTime=e,e===t&&(t+=1e-4),l>=16?l--:l++;const g=Pn(c.trim()),f=Ai(e,t,g);a!=null&&(u=a.cues)!=null&&u.getCueById(f)||(n=new h(e,t,g),n.id=f,n.line=d+1,n.align="left",n.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(n))}return a&&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=>sn(a,d))),i}},Bh={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},Wn=Le(Le({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:Vn,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:dl,bufferController:pc,capLevelController:Ri,errorController:el,fpsController:Vc,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:Kr,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:Bh},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},Gh()),{},{subtitleStreamController:dc,subtitleTrackController:gc,timelineController:Kc,audioStreamController:hc,audioTrackController:uc,emeController:Lt,cmcdController:bh,contentSteeringController:Dh});function Gh(){return{cueHandler:Uh,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 $h(a,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const t=ni(a),s=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];
26return s.forEach(r=>{const n=`${r==="level"?"playlist":r}LoadPolicy`,o=e[n]===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[n].default;switch(e[n]={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&&S.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${n}": ${JSON.stringify(e[n])}`)}),Le(Le({},t),e)}function ni(a){return a&&typeof a=="object"?Array.isArray(a)?a.map(ni):Object.keys(a).reduce((e,t)=>(e[t]=ni(a[t]),e),{}):a}function Kh(a){const e=a.loader;e!==Cr&&e!==Vn?(S.log("[config]: Custom loader detected, cannot enable progressive streaming"),a.progressive=!1):_h()&&(a.loader=Cr,a.progressive=!0,a.enableSoftwareAES=!0,S.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Ks;class Hh extends gi{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={},n={};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&&(Ks||(Ks=/chrome|firefox/i.test(navigator.userAgent)),Ks&&(h.audioCodec=f=void 0)),f&&(h.audioCodec=f=os(f,s)),((d=m)==null?void 0:d.indexOf("avc1"))===0&&(m=h.videoCodec=Co(m));const{width:E,height:T,unknownCodecs:y}=h;if(o||(o=!!(E&&T)),l||(l=!!m),c||(c=!!f),y!=null&&y.length||f&&!Is(f,"audio",s)||m&&!Is(m,"video",s))return;const{CODECS:v,"FRAME-RATE":A,"HDCP-LEVEL":x,"PATHWAY-ID":D,RESOLUTION:R,"VIDEO-RANGE":C}=g,I=`${`${D||"."}-`}${h.bitrate}-${R}-${A}-${v}-${C}-${x}`;if(r[I])if(r[I].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const w=n[I]+=1;h.attrs["PATHWAY-ID"]=new Array(w+1).join(".");const B=new Rt(h);r[I]=B,i.push(B)}else r[I].addGroupId("audio",g.AUDIO),r[I].addGroupId("text",g.SUBTITLES);else{const w=new Rt(h);r[I]=w,n[I]=1,i.push(w)}}),this.filterAndSortMediaOptions(i,t,o,l,c)}filterAndSortMediaOptions(e,t,s,i,r){let n=[],o=[],l=e;if((s||i)&&r&&(l=l.filter(({videoCodec:f,videoRange:m,width:E,height:T})=>(!!f||!!(E&&T))&&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:W.MEDIA_ERROR,details:b.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:f,reason:f.message})}});return}if(t.audioTracks){const{preferManagedMediaSource:f}=this.hls.config;n=t.audioTracks.filter(m=>!m.audioCodec||Is(m.audioCodec,"audio",f)),_r(n)}t.subtitles&&(o=t.subtitles,_r(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 ls.indexOf(f.videoRange)-ls.indexOf(m.videoRange);
26if(f.videoCodec!==m.videoCodec){const E=Ni(f.videoCodec),T=Ni(m.videoCodec);if(E!==T)return T-E}if(f.uri===m.uri&&f.codecSet!==m.codecSet){const E=as(f.codecSet),T=as(m.codecSet);if(E!==T)return T-E}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;f<c.length;f++)if(c[f].pathwayId===l[0].pathwayId){h=c[f];break}}this._levels=l;for(let f=0;f<l.length;f++)if(l[f]===h){var u;this._firstLevel=f;const m=h.bitrate,E=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${l.length} level(s) found, first bitrate: ${m}`),((u=this.hls.userConfig)==null?void 0:u.abrEwmaDefaultEstimate)===void 0){const T=Math.min(m,this.hls.config.abrEwmaDefaultEstimateMax);T>E&&E===Wn.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}const d=r&&!i,g={levels:l,audioTracks:n,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:r,video:i,altAudio:!d&&n.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:W.OTHER_ERROR,details:b.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,n=t[e],o=n.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=n,s===e&&n.details&&i&&r===o)return;this.log(`Switching to level ${e} (${n.height?n.height+"p ":""}${n.videoRange?n.videoRange+" ":""}${n.codecSet?n.codecSet+" ":""}@${n.bitrate})${o?" with Pathway "+o:""} from level ${s}${r?" with Pathway "+r:""}`);const l={level:e,attrs:n.attrs,details:n.details,bitrate:n.bitrate,averageBitrate:n.averageBitrate,maxBitrate:n.maxBitrate,realBitrate:n.realBitrate,width:n.width,height:n.height,codecSet:n.codecSet,audioCodec:n.audioCodec,videoCodec:n.videoCodec,audioGroups:n.audioGroups,subtitleGroups:n.subtitleGroups,loaded:n.loaded,loadError:n.loadError,fragmentError:n.fragmentError,name:n.name,id:n.id,uri:n.uri,url:n.url,urlId:0,audioGroupIds:n.audioGroupIds,textGroupIds:n.textGroupIds};this.hls.trigger(p.LEVEL_SWITCHING,l);const c=n.details;if(!c||c.live){const h=this.switchParams(n.uri,i?.details,c);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===te.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===H.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,n=this._levels[i];if(!n){var o;this.warn(`Invalid level index ${i}`),(o=t.deliveryDirectives)!=null&&o.skip&&(r.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(n.fragmentError===0&&(n.loadError=0),this.playlistLoaded(i,t,n.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(n){this.warn(`Could not construct new URL with HLS Delivery Directives: ${n}`)}const r=s.attrs["PATHWAY-ID"];this.log(`Loading level index ${t}${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.forEac
vendor: 4,408 bytes, line 26
26h(n=>n.level=-1)),!1));on(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 _r(a){const e={};a.forEach(t=>{const s=t.groupId||"";t.id=e[s]=e[s]||0,e[s]++})}class Vh{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=b.KEY_LOAD_ERROR,s,i,r){return new it({type:W.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:r,error:s,networkDetails:i})}loadClear(e,t){if(this.emeController&&this.config.emeEnabled){const{sn:s,cc:i}=e;for(let r=0;r<t.length;r++){const n=t[r];if(i<=n.cc&&(s==="initSegment"||n.sn==="initSegment"||s<n.sn)){this.emeController.selectKeySystemFormat(n).then(o=>{n.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var 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,b.KEY_LOAD_ERROR,c))}const n=r.uri;if(!n)return Promise.reject(this.createKeyLoadError(e,b.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${n}"`)));let o=this.keyUriToKeyInfo[n];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[n]={decryptdata:r,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},r.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return r.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,b.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((n,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:E,keyInfo:T,url:y}=f;if(!E.decryptdata||T!==this.keyUriToKeyInfo[y])return o(this.createKeyLoadError(E,b.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),m));T.decryptdata.key=E.decryptdata.key=new Uint8Array(d.data),E.keyLoader=null,T.loader=null,n({frag:E,keyInfo:T})},onError:(d,g,f,m)=>{this.resetLoader(g),o(this.createKeyLoadError(t,b.KEY_LOAD_ERROR,new Error(`HTTP Error ${d.code} loading key ${d.text}`),f,Le({url:l.url,data:void 0},d)))},onTimeout:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,b.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),f))},onAbort:(d,g,f)=>{this.resetLoader(g),o(this.createKeyLoadError(t,b.INTERNAL_ABORTED,new Error("key loading aborted"),f))}};r.load(l,h,u)})}
26resetLoader(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 Yn(){return self.SourceBuffer||self.WebKitSourceBuffer}function jn(){if(!gt())return!1;const e=Yn();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function Wh(){if(!jn())return!1;const a=gt();return typeof a?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>a.isTypeSupported(Ft(e,"video")))||["mp4a.40.2","fLaC"].some(e=>a.isTypeSupported(Ft(e,"audio"))))}function Yh(){var a;const e=Yn();return typeof(e==null||(a=e.prototype)==null?void 0:a.changeType)=="function"}const jh=250,is=2,zh=.1,qh=.05;class Xh{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:n,seeking:o}=i,l=this.seeking&&!o,c=!this.seeking&&o;if(this.seeking=o,n!==e){if(this.moved=!0,o||(this.nudgeRetry=0),r!==null){if(this.stallReported){const E=self.performance.now()-r;S.warn(`playback not stuck anymore @${n}, after ${Math.round(E)}ms`),this.stallReported=!1}this.stalled=null}return}if(c||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!ne.getBuffered(i).length){this.nudgeRetry=0;return}const h=ne.bufferInfo(i,n,0),u=h.nextStart||0;if(o){const E=h.len>is,T=!u||t&&t.start<=n||u-n>is&&!this.fragmentTracker.getPartialFragment(n);if(E||T)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var d;if(!(h.len>0)&&!u)return;const T=Math.max(u,h.start||0)-n,y=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,A=(y==null||(d=y.details)==null?void 0:d.live)?y.details.targetduration*2:is,x=this.fragmentTracker.getPartialFragment(n);if(T>0&&(T<=A||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>=jh&&(this._reportStall(h),!this.media))return;const m=ne.bufferInfo(i,n,s.maxBufferHole);this._tryFixBufferStall(m,f)}_tryFixBufferStall(e,t){const{config:s,fragmentTracker:i,media:r}=this;if(r===null)return;const n=r.currentTime,o=i.getPartialFragment(n);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>s.maxBufferHole||e.nextStart&&e.nextStart-n<s.maxBufferHole)&&t>s.highBufferWatchdogPeriod*1e3&&(S.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)})`);S.warn(r.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.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,n=ne.bufferInfo(i,r,0),o=r<n.start?n.start:n.nextStart;if(o){const l=n.len<=t.maxBufferHole,c=n.len>0&&n.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,H.MAIN);f&&o<f.end&&(g=!0)}if(!g){const f=e||d.getAppendedFrag(r,H.MAIN);if(f){let m=!1,E=f.end;for(;E<o;){const T=d.getPartialFragment(E);if(T)E+=T.duration;else{m=!0;break}}if(m)return 0}}}const u=Math.max(o+qh,r+zh);if(S.warn(`skipping hole, adjusting currentTime from ${r} to ${u}`),this.moved=!0,this.stalled=null,i.currentTime=u,e&&!e.gap){const d=new Error(`fragment loaded with buffer holes, seeking from ${r} to ${u}`);s.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:e})}return u}}return 0}_tryNudgeBuffer(){const{config:e,hls:t,media:s,nudgeRetry:i}=this;if(s===null)return;const r=s.currentTime;if(this.nudgeRetry++,i<e.nudgeMaxRetry){const n=r+(i+1)*e.nudgeOffset,o=new Error(`Nudging 'currentTime' from ${r} to ${n}`);S.warn(o.message),s.currentTime=n,t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_NUDGE_ON_STALL,error:o,fatal:!1})}else{const n=new Error(`Playhead still not moving while enough data buffered @${r} after ${e.nudgeMaxRetry} nudges`);S.error(n.message),t.trigger(p.ERROR,{type:W.MEDIA_ERROR,details:b.BUFFER_STALLED_ERROR,error:n,fatal:!0})}}}const Qh=100;
26class Jh extends Ei{constructor(e,t,s){super(e,t,s,"[stream-controller]",H.MAIN),this.audioCodecSwap=!1,this.gapController=null,this.level=-1,this._forceStartLoad=!1,this.altAudio=!1,this.audioOnly=!1,this.fragPlaying=null,this.onvplaying=null,this.onvseeked=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(p.MANIFEST_LOADING,this.onManifestLoading,this),e.on(p.MANIFEST_PARSED,this.onManifestParsed,this),e.on(p.LEVEL_LOADING,this.onLevelLoading,this),e.on(p.LEVEL_LOADED,this.onLevelLoaded,this),e.on(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(p.ERROR,this.onError,this),e.on(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(p.BUFFER_CREATED,this.onBufferCreated,this),e.on(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(p.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(p.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(p.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(p.MANIFEST_LOADING,this.onManifestLoading,this),e.off(p.MANIFEST_PARSED,this.onManifestParsed,this),e.off(p.LEVEL_LOADED,this.onLevelLoaded,this),e.off(p.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(p.ERROR,this.onError,this),e.off(p.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(p.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(p.BUFFER_CREATED,this.onBufferCreated,this),e.off(p.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(p.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(p.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this._unregisterListeners(),super.onHandlerDestroying()}startLoad(e){if(this.levels){const{lastCurrentTime:t,hls:s}=this;if(this.stopLoad(),this.setInterval(Qh),this.level=-1,!this.startFragRequested){let i=s.startLevel;i===-1&&(s.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=s.firstAutoLevel),s.nextLoadLevel=i,this.level=s.loadLevel,this.loadedmetadata=!1}t>0&&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?.[s],r=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,n=i?.[r];this.resetStartWhenNotLoaded(n||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;if(t===null||!i&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const r=e.nextLoadLevel;if(!(s!=null&&s[r]))return;const n=s[r],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const m={};this.altAudio&&(m.type="video"),this.hls.trigger(p.BUFFER_EOS,m),this.state=_.ENDED;return}e.loadLevel!==r&&e.manualLevel===-1&&this.log(`Adapting to level ${r} from level ${this.level}`),this.level=e.nextLoadLevel=r;const c=n.details;if(!c||this.state===_.WAITING_LEVEL||c.live&&this.levelLastLoaded!==n){this.level=r,this.state=_.WAITING_LEVEL;return}const h=o.len,u=this.getMaxBufferLength(n.maxBitrate);if(h>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const d=this.backtrackFragment?this.backtrackFragment.start:o.end;let g=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&g&&g.sn!=="initSegment"&&this.fragmentTracker.getState(g)!==xe.OK){var f;const E=((f=this.backtrackFragment)!=null?f:g).sn-c.startSN,T=c.fragments[E-1];T&&g.cc===T.cc&&(g=T,this.fragmentTracker.removeFragment(T))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,d)){if(!g.gap){const E=this.audioOnly&&!this.altAudio?ie.AUDIO:ie.VIDEO,T=(E===ie.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;T&&this.afterBufferFlushed(T,E,H.MAIN)}g=this.getNextFragmentLoopLoading(g,c,o,H.MAIN,u)}g&&(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,n,d))}loadFragment(e,t,s){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===xe.NOT_LOADED||i===xe.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,H.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<r.targetduration*2)return}if(!t.paused&&e){const o=this.hls.nextLoadLevel,l=e[o],c=this.fragLastKbps;c&&this.fragCurrent?s=this.fragCurrent.duration*l.maxBitrate/(1e3*c)+1:s=0}else s=0;const n=this.getBufferedFrag(t.currentTime+s);if(n){const o=this.followingBufferedFrag(n);if(o){this.abortCurrentFrag();const l=o.maxStartPTS?o.maxStartPTS:o.start,c=o.duration,h=Math.max(n.end,l+Math.min(Math.max(c-this.config.maxFragLookUpTolerance,c*(this.couldBacktrack?.5:.125)),c*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case _.KEY_LOADING:case _.FRAG_LOADING:case _.FRAG_LOADING_WAITING_RETRY:case _.PARSING:case _.PARSED:this.state=_.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const s=t.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),s.addEventListener("playing",this.onvplaying),s.addEventListener("seeked",this.onvseeked),this.gapController=new Xh(this.config,s,this.fragmentTracker,this.hls)}onMediaDetaching(){const{media:e}=this;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),super.onMediaDetaching()}onMediaPlaying(){this.tick()}onMediaSeeked(){const e=this.media,t=e?e.currentTime:null;N(t)&&this.log(`Media seeked to ${t.toFixed(3)}`);const s=this.getMainFwdBufferInfo();if(s===null||s.len===0){this.warn(`Main forward buffer length on "seeked" event ${s?s.len:"empty"})`);return}this.tick()}onManifestLoading(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(p.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=this.fragLastKbps=0,this.levels=this.fragPlaying=this.backtrackFragment=this.levelLastLoaded=null,this.altAudio=this.audioOnly=this.startFragRequested=!1}onManifestParsed(e,t){let s=!1,i=!1;
26t.levels.forEach(r=>{const n=r.audioCodec;n&&(s=s||n.indexOf("mp4a.40.2")!==-1,i=i||n.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=s&&i&&!Yh(),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,n=t.details,o=n.totalduration;if(!i){this.warn(`Levels were reset while loading level ${r}`);return}this.log(`Level ${r} loaded [${n.startSN},${n.endSN}]${n.lastPartSn?`[part-${n.lastPartSn}-${n.lastPartIndex}]`:""}, cc [${n.startCC}, ${n.endCC}] duration:${o}`);const l=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(n.live||(s=l.details)!=null&&s.live){var u;if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;h=this.alignPlaylists(n,l.details,(u=this.levelLastLoaded)==null?void 0:u.details)}if(l.details=n,this.levelLastLoaded=l,this.hls.trigger(p.LEVEL_UPDATED,{details:n,level:r}),this.state===_.WAITING_LEVEL){if(this.waitForCdnTuneIn(n))return;this.state=_.IDLE}this.startFragRequested?n.live&&this.synchronizeToLiveEdge(n):this.setStartPosition(n,h),this.tick()}_handleFragmentLoadProgress(e){var t;const{frag:s,part:i,payload:r}=e,{levels:n}=this;if(!n){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=n[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 In(this.hls,H.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,m=f!==-1,E=new mi(s.level,s.sn,s.stats.chunkCount,r.byteLength,f,m),T=this.initPTS[s.cc];g.push(r,u,d,c,s,i,l.totalduration,h,E,T)}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 n=this.fragCurrent;n&&(this.log("Switching to main audio track, cancel main fragment load"),n.abortRequests(),this.fragmentTracker.removeFragment(n)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const r=this.hls;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,n=!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 n=!0}n&&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!==H.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 b.FRAG_GAP:case b.FRAG_PARSING_ERROR:case b.FRAG_DECRYPT_ERROR:case b.FRAG_LOAD_ERROR:case b.FRAG_LOAD_TIMEOUT:case b.KEY_LOAD_ERROR:case b.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.MAIN,t);break;case b.LEVEL_LOAD_ERROR:case b.LEVEL_LOAD_TIMEOUT:case b.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===_.WAITING_LEVEL&&((s=t.context)==null?void 0:s.type)===te.LEVEL&&(this.state=_.IDLE);break;case b.BUFFER_APPEND_ERROR:case b.BUFFER_FULL_ERROR:if(!t.parent||t.parent!=="main")return;if(t.details===b.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(t)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case b.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}
26checkBuffer(){const{media:e,gapController:t}=this;if(!(!e||!t||!e.readyState)){if(this.loadedmetadata||!ne.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!==ie.AUDIO||this.audioOnly&&!this.altAudio){const s=(t===ie.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(s,t,H.MAIN),this.tick()}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let s=this.startPosition;if(s>=0&&t<s){if(e.seeking){this.log(`could not seek to ${s}, already seeking at ${t}`);return}const i=ne.getBuffered(e),n=(i.length?i.start(0):0)-s;n>0&&(n<this.config.maxBufferHole||n<this.config.maxFragLookUpTolerance)&&(this.log(`adjusting start position by ${n} to match buffer start`),s+=n,this.startPosition=s),this.log(`seek to target start position ${s} from current time ${t}`),e.currentTime=s}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(s=>{const{hls:i}=this;if(!s||this.fragContextChanged(e))return;t.fragmentError=0,this.state=_.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const r=e.stats;r.parsing.start=r.parsing.end=r.buffering.start=r.buffering.end=self.performance.now(),i.trigger(p.FRAG_LOADED,s),e.bitrateTest=!1})}_handleTransmuxComplete(e){var t;const s="main",{hls:i}=this,{remuxResult:r,chunkMeta:n}=e,o=this.getCurrentContext(n);if(!o){this.resetWhenMissingContext(n);return}const{frag:l,part:c,level:h}=o,{video:u,text:d,id3:g,initSegment:f}=r,{details:m}=h,E=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 v=l.initSegment||l;this._bufferInitSegment(h,f.tracks,v,n),i.trigger(p.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:s,tracks:f.tracks})}const T=f.initPTS,y=f.timescale;N(T)&&(this.initPTS[l.cc]={baseTime:T,timescale:y},i.trigger(p.INIT_PTS_FOUND,{frag:l,id:s,initPTS:T,timescale:y}))}if(u&&m&&l.sn!=="initSegment"){const T=m.fragments[l.sn-1-m.startSN],y=l.sn===m.startSN,v=!T||l.cc>T.cc;if(r.independent!==!1){const{startPTS:A,endPTS:x,startDTS:D,endDTS:R}=u;if(c)c.elementaryStreams[u.type]={startPTS:A,endPTS:x,startDTS:D,endDTS:R};else if(u.firstKeyFrame&&u.independent&&n.id===1&&!v&&(this.couldBacktrack=!0),u.dropped&&u.independent){const C=this.getMainFwdBufferInfo(),k=(C?C.end:this.getLoadPosition())+this.config.maxBufferHole,I=u.firstKeyFramePTS?u.firstKeyFramePTS:A;if(!y&&k<I-this.config.maxBufferHole&&!v){this.backtrack(l);return}else v&&(l.gap=!0);l.setElementaryStreamInfo(u.type,l.start,x,l.start,R,!0)}else y&&A>is&&(l.gap=!0);l.setElementaryStreamInfo(u.type,A,x,D,R),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(u,l,c,n,y||v)}else if(y||v)l.gap=!0;else{this.backtrack(l);return}}if(E){const{startPTS:T,endPTS:y,startDTS:v,endDTS:A}=E;c&&(c.elementaryStreams[ie.AUDIO]={startPTS:T,endPTS:y,startDTS:v,endDTS:A}),l.setElementaryStreamInfo(ie.AUDIO,T,y,v,A),this.bufferFragmentData(E,l,c,n)}if(m&&g!=null&&(t=g.samples)!=null&&t.length){const T={id:s,frag:l,details:m,samples:g.samples};i.trigger(p.FRAG_PARSING_METADATA,T)}if(m&&d){const T={id:s,frag:l,details:m,samples:d.samples};i.trigger(p.FRAG_PARSING_USERDATA,T)}}_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:n,audiovideo:o}=t;if(r){let l=e.audioCodec;const c=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const h=r.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==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}]`)}n&&(n.levelCodec=e.videoCodec,n.id="main",this.log(`Init video buffer, container:${n.container}, codecs[level/parsed]=[${e.videoCodec||""}/${n.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(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,H.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(ne.isBuffered(e,s)?t=this.getAppendedFrag(s):ne.isBuffered(e,s+.1)&&
26(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&&N(t)&&N(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 $e{static get version(){return"1.5.13"}static isMSESupported(){return jn()}static isSupported(){return Wh()}static getMediaSource(){return gt()}static get Events(){return p}static get ErrorTypes(){return W}static get ErrorDetails(){return b}static get DefaultConfig(){return $e.defaultConfig?$e.defaultConfig:Wn}static set DefaultConfig(e){$e.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 Si,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,Ba(e.debug||!1,"Hls instance");const t=this.config=$h($e.DefaultConfig,e);this.userConfig=e,t.progressive&&Kh(t);const{abrController:s,bufferController:i,capLevelController:r,errorController:n,fpsController:o}=t,l=new n(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,E=m?new m(this):null,T=this.levelController=new Hh(this,E),y=new gl(this),v=new Vh(this.config),A=this.streamController=new Jh(this,y,v);u.setStreamController(A),d.setStreamController(A);const x=[g,T,A];E&&x.splice(1,0,E),this.networkControllers=x;const D=[c,h,u,d,f,y];this.audioTrackController=this.createController(t.audioTrackController,x);const R=t.audioStreamController;R&&x.push(new R(this,y,v)),this.subtitleTrackController=this.createController(t.subtitleTrackController,x);const C=t.subtitleStreamController;C&&x.push(new C(this,y,v)),this.createController(t.timelineController,D),v.emeController=this.emeController=this.createController(t.emeController,D),this.cmcdController=this.createController(t.cmcdController,D),this.latencyController=this.createController(Go,D),this.coreComponents=D,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(S.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:W.OTHER_ERROR,details:b.INTERNAL_EXCEPTION,fatal:i,event:e,error:s}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){S.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.forEac
26h(t=>t.destroy()),this.coreComponents.length=0;const e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){S.log("attachMedia"),this._media=e,this.trigger(p.MEDIA_ATTACHING,{media:e})}detachMedia(){S.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=ci.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,S.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){S.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(t=>{t.startLoad(e)})}stopLoad(){S.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){S.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){S.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){S.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){S.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){S.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){S.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){S.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(S.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){$o(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<s;i++)if(e[i].maxBitrate>=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 n=e[r].attrs["HDCP-LEVEL"];if(n&&n<=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}}$e.defaultConfig=void 0;var Zh=Oe('<time id="trim-duration" class="svelte-1ffmt2w"> </time>'),eu=Oe('<div class="component-wrapper svelte-1ffmt2w"><div class="waveform-container svelte-1ffmt2w"><div id="waveform" class="svelte-1ffmt2w"></div></div> <div class="timestamps svelte-1ffmt2w"><time id="time" class="svelte-1ffmt2w">0:00</time> <div><!> <time id="duration" class="svelte-1ffmt2w">0:00</time></div></div> <div class="subtitle-display svelte-1ffmt2w" data-testid="subtitle-display"></div> <!></div>'),tu=Oe('<audio controls preload="metadata"></audio> <!>',1);function su(a,e){ms(e,!0);let t=se(e,"value",3,null),s=se(e,"subtitles",3,null),i=se(e,"dispatch_blob",3,()=>Promise.resolve()),r=se(e,"interactive",3,!1),n=se(e,"editable",3,!0),o=se(e,"trim_region_settings",19,()=>({})),l=se(e,"mode",15),c=se(e,"handle_reset_value",3,()=>{}),h=se(e,"playback_position",15),u=nt(()=>t()?.url),d=_e(0),g,f,m=_e(!1),E,T=_e(!1),y,v,A,x=_e(0),D=_e(0),R=_e(!1),C,k=!1,I=_e(!0),w=[],B=nt(()=>e.waveform_options.show_recording_waveform&&!t()?.is_stream);Ke(()=>{P(m)&&h()!==void 0&&P(d)!==h()&&P(x)&&(f?.seekTo(h()/P(x)),ge(d,h(),!0))});const F=()=>{f=oa.create({container:g,...e.waveform_settings}),s()&&f&&(P(I)?Z(f,s()):q()),f?.on("init",()=>{ge(m,!0)}),f?.on("decode",$=>{ge(x,$,!0),A&&(A.textContent=Mt($))});let Y=!0;f?.on("timeupdate",$=>{if(v&&(v.textContent=Mt($)),Y){Y=!1;return}h($),ge(d,$,!0)}),f?.on("interaction",()=>{const $=f?.getCurrentTime()||0;
26v&&(v.textContent=Mt($)),h($),ge(d,$,!0)}),f?.on("ready",()=>{e.waveform_settings.autoplay?f?.play():f?.stop()}),f?.on("finish",()=>{e.loop?f?.play():(ge(T,!1),e.onstop?.())}),f?.on("pause",()=>{ge(T,!1),e.onpause?.()}),f?.on("play",()=>{ge(T,!0),e.onplay?.()}),f?.on("load",()=>{e.onload?.()})};Ke(()=>{P(u)&&P(m)&&ea(()=>{t()?.url&&f&&f.load(t().url).catch(Y=>{Y.name!=="AbortError"&&console.error("Waveform load error:",Y)})})});const G=async(Y,$)=>{l("");const fe=f?.getDecodedData();if(fe){const oe=await la(fe,Y,$,e.waveform_settings.sampleRate);await i()([oe],"change")}e.onedit?.()};async function V(Y){k=!1,e.waveform_options.show_recording_waveform?f?.load(Y):C&&(C.src=Y)}Ke(()=>{s()&&f&&(P(I)?Z(f,s()):q())});function U(Y){if(!(!Y||!Y.is_stream||!Y.url))if($e.isSupported()&&!k){const $=new $e({maxBufferLength:1,maxMaxBufferLength:1,lowLatencyMode:!0});$.loadSource(Y.url),$.attachMedia(C),$.on($e.Events.MANIFEST_PARSED,function(){e.waveform_settings.autoplay&&C.play()}),$.on($e.Events.ERROR,function(fe,oe){if(console.error("HLS error:",fe,oe),oe.fatal)switch(oe.type){case $e.ErrorTypes.NETWORK_ERROR:console.error("Fatal network error encountered, trying to recover"),$.startLoad();break;case $e.ErrorTypes.MEDIA_ERROR:console.error("Fatal media error encountered, trying to recover"),$.recoverMediaError();break;default:console.error("Fatal error, cannot recover"),$.destroy();break}}),k=!0}else k||(C.src=Y.url,e.waveform_settings.autoplay&&C.play(),k=!0)}Ke(()=>{C&&P(u)&&P(m)&&P(u)&&V(P(u))}),Ke(()=>{C&&t()?.is_stream&&U(t())}),oi(()=>{F();const Y=$=>{!f||P(R)||!(E&&E.contains(document.activeElement))||($.key==="ArrowRight"&&l()!=="edit"?Ii(f,.1):$.key==="ArrowLeft"&&l()!=="edit"&&Ii(f,-.1))};return window.addEventListener("keydown",Y),()=>{f?.destroy(),window.removeEventListener("keydown",Y)}});async function Z(Y,$){O();try{let fe;if(Array.isArray($))fe=$;else{const be=await(await fetch($)).text();fe=M(be)}if(fe.length>0){let oe="";if(y){y.style.display="";const be=Me=>{const Ne=fe.find(et=>Me>=et.start&&Me<=et.end);Ne&&Ne.text!==oe?(oe=Ne.text,y.textContent=oe):!Ne&&oe!==""&&(oe="",y.textContent="")};Y.on("audioprocess",be),w.push(()=>{Y.un("audioprocess",be)})}}}catch{}}function q(){y&&(y.style.display="none")}function O(){y&&(y.textContent=""),w.forEach(Y=>Y()),w=[]}function M(Y){const $=Y.split(`
27`),fe=[];for(let oe=0;oe<$.length;oe++){const be=$[oe].trim();if(be.includes(" --> ")){const[Me,Ne]=be.split(" --> "),et=ee(Me),z=ee(Ne);let J="";for(let he=oe+1;he<$.length&&$[he].trim()!=="";he++)J&&(J+=" "),J+=$[he].trim();J&&fe.push({start:et,end:z,text:J})}}return fe}function ee(Y){const $=Y.split(":");if($.length===3){const fe=parseInt($[0]),oe=parseInt($[1]),be=parseFloat($[2]);return fe*3600+oe*60+be}return 0}var j=tu(),X=lt(j);let ae;ht(X,Y=>C=Y,()=>C);var re=ve(X,2);{var de=Y=>{Or(Y,{size:"small",children:($,fe)=>{Vs($)},$$slots:{default:!0}})},Re=Y=>{var $=Fr(),fe=lt($);{var oe=be=>{var Me=eu(),Ne=Te(Me),et=Te(Ne);let z;ht(et,ue=>g=ue,()=>g),ye(Ne);var J=ve(Ne,2),he=Te(J);ht(he,ue=>v=ue,()=>v);var Ue=ve(he,2),Ot=Te(Ue);{var ys=ue=>{var Pe=Zh(),zn=Te(Pe,!0);ye(Pe),xt(qn=>Pr(zn,qn),[()=>Mt(P(D))]),Se(ue,Pe)};Fe(Ot,ue=>{l()==="edit"&&P(D)>0&&ue(ys)})}var vs=ve(Ot,2);ht(vs,ue=>A=ue,()=>A),ye(Ue),ye(J);var ke=ve(J,2);ht(ke,ue=>y=ue,()=>y);var De=ve(ke,2);{let ue=nt(()=>s()!==null);_a(De,{get container(){return g},get waveform(){return f},get playing(){return P(T)},get audio_duration(){return P(x)},get i18n(){return e.i18n},get interactive(){return r()},handle_trim_audio:G,get show_redo(){return r()},get handle_reset_value(){return c()},get waveform_options(){return e.waveform_options},get trim_region_settings(){return o()},get editable(){return n()},get show_subtitles(){return P(ue)},get mode(){return l()},set mode(Pe){l(Pe)},get trimDuration(){return P(D)},set trimDuration(Pe){ge(D,Pe,!0)},get show_volume_slider(){return P(R)},set show_volume_slider(Pe){ge(R,Pe,!0)},get subtitles_toggle(){return P(I)},set subtitles_toggle(Pe){ge(I,Pe,!0)}})}ye(Me),ht(Me,ue=>E=ue,()=>E),xt(()=>{Ct(Me,"data-testid",e.label?"waveform-"+e.label:"unlabelled-audio"),z=Hs(et,"",z,{height:g?null:"58px"})}),Se(be,Me)};Fe(fe,be=>{P(B)&&be(oe)},!0)}Se(Y,$)};Fe(re,Y=>{t()===null?Y(de):Y(Re,!1)})}xt(()=>{ae=wr(X,1,"standard-player svelte-1ffmt2w",null,ae,{hidden:P(B)}),X.autoplay=e.waveform_settings.autoplay}),xs("load",X,function(...Y){e.onload?.apply(this,Y)}),xs("ended",X,()=>e.onstop?.()),xs("play",X,()=>e.onplay?.()),Se(a,j),ps()}var iu=Oe("<!> <!>",1),ru=Oe("<!> <!>",1),nu=Oe("<!> <!>",1);function au(a,e){ms(e,!0);let t=se(e,"value",3,null),s=se(e,"subtitles",3,null),i=se(e,"show_label",3,!0),r=se(e,"buttons",19,()=>[]),n=se(e,"on_custom_button_click",3,null),o=se(e,"waveform_settings",19,()=>({})),l=se(e,"waveform_options",19,()=>({show_recording_waveform:!0})),c=se(e,"editable",3,!0),h=se(e,"display_icon_button_wrapper_top_corner",3,!1),u=se(e,"minimal",3,!1),d=se(e,"playback_position",15);Ke(()=>{t()&&e.onchange?.(t())});var g=nu(),f=lt(g);{let y=nt(()=>e.label||e.i18n("audio.audio"));sa(f,{get show_label(){return i()},get Icon(){return Vs},float:!1,get label(){return P(y)}})}var m=ve(f,2);{var E=y=>{var v=Fr(),A=lt(v);{var x=R=>{{let C=nt(()=>e.label||e.i18n("audio.audio"));ca(R,{get value(){return t()},get label(){return P(C)},get loop(){return e.loop}})}},D=R=>{var C=ru(),k=lt(C);aa(k,{get display_top_corner(){return h()},get buttons(){return r()},get on_custom_button_click(){return n()},children:(w,B)=>{var F=iu(),G=lt(F);{var V=q=>{{let O=nt(()=>t().is_stream?t().url?.replace("playlist.m3u8","playlist-file"):t().url),M=nt(()=>t().orig_name||t().path);ia(q,{get href(){return P(O)},get download(){return P(M)},children:(ee,j)=>{{let X=nt(()=>e.i18n("common.download"));ta(ee,{get Icon(){return na},get label(){return P(X)}})}},$$slots:{default:!0}})}};Fe(G,q=>{r().some(O=>typeof O=="string"&&O==="download")&&q(V)})}var U=ve(G,2);{var Z=q=>{ra(q,{get i18n(){return e.i18n}
27,get onerror(){return e.onerror},get onshare(){return e.onshare},formatter:async O=>!O||!O.url?"":`<audio controls src="${await Jn(O.url)}"></audio>`,get value(){return t()}})};Fe(U,q=>{r().some(O=>typeof O=="string"&&O==="share")&&q(Z)})}Se(w,F)},$$slots:{default:!0}});var I=ve(k,2);{let w=nt(()=>Array.isArray(s())?s():s()?.url);su(I,{get value(){return t()},get subtitles(){return P(w)},get label(){return e.label},get i18n(){return e.i18n},get waveform_settings(){return o()},get waveform_options(){return l()},get editable(){return c()},get loop(){return e.loop},get onpause(){return e.onpause},get onplay(){return e.onplay},get onstop(){return e.onstop},onload:()=>{},get playback_position(){return d()},set playback_position(B){d(B)}})}Se(R,C)};Fe(A,R=>{u()?R(x):R(D,!1)})}Se(y,v)},T=y=>{Or(y,{size:"small",children:(v,A)=>{Vs(v)},$$slots:{default:!0}})};Fe(m,y=>{t()!==null?y(E):y(T,!1)})}Se(a,g),ps()}const Lu=Object.freeze(Object.defineProperty({__proto__:null,default:au},Symbol.toStringTag,{value:"Module"}));export{su as A,au as S,_a as W,Lu as a};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.